0

If I have two columns, prices (full_price, sales_price), and these columns has numbers in them. I know that sql statements can do multiple order by's but how does it work when these columns have values in them?

("SELECT * FROM table ORDER BY full_price,sales_price DESC")

How do I accomplish so it will pick the smallest value of the two columns? and it will place the data in order based on the chosen column between full_price and sales_price?

Note: sometimes sales_price will have no value.

Thanks

Edit:

Example

id    full_price        sales_price
1      23                 42           
2      342                200
3      1
4      10                 8

What I'm trying to do is with these numbers, I can output data associated with the lowest price.

The order should be:

3,4,1,2

Reason:

3: 1
4: 8
1: 23
2: 200
1
  • I edited to show an example, thank you Commented Jul 25, 2012 at 5:10

3 Answers 3

4

Assuming that your blank sales_price is a NULL and that full_price cannot be NULL:

select ...
from ...
where ...
order by case
    when sales_price is null then full_price
    else least(full_price, sales_price)
end

You probably want to add a secondary sort key to get consistent and sensible results from ties.

Sign up to request clarification or add additional context in comments.

2 Comments

how would i add another sort key? do i add it into the case or is it after the end?
@andrewliu: You'd add the second sort key after then end: order by case ... end, some_other_column
1
SELECT * FROM table
ORDER BY case when sales_price is null or full_price is null
              then 0
              when full_price > sales_price
              then sales_price ASC
              else full_price ASC
         end

Comments

0

If you want results based on difference of full_price and sales_price then try:

SELECT *
FROM table
ORDER BY ABS(full_price - IF(sales_price IS NULL, 0, sales_price)) ASC

or if you want results based on comparision of full_price and sales_price then try:

SELECT *
FROM table
ORDER BY IF(full_price < IF(sales_price IS NULL, 0, sales_price), 
            full_price , sales_price ) ASC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.