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
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.
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
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