I have some problems with Ordering in my SQL query.
I have 2 fields ('price' and 'in_stock')in table 'products'. What I want to do is to sort my query result by this 2 fields - by 'in_stock' and than by 'price'. BUT(!) one important thing is to order 'in_stock' as boolen. For example the table is:
Name | Price | in_stock |
----------------------------------|
Product1 | 100 | 9 |
Product2 | 200 | 0 |
Product3 | 500 | 4 |
Product4 | 500 | 0 |
Product5 | 300 | 2 |
So right order result is:
Product1 - 100, 9
Product5 - 300, 2
Product3 - 500, 4
Product2 - 200, 0
Product4 - 500, 0
First step - order products by stock - if product out of stock it must be at the end of list. After sort products by price - from lowest to highest.
您可以通过在ORDER子句中添加两列来按两列排序:
ORDER BY in_stock DESC, price ASC
You can use conditions in your order by
clause:
select name, price, in_stock
from yourtable
order by in_stock = 0, price
This will order the products that have stock first (regardless of how many), then ordered by price.
Or you could use a case statement to order the results:
order by case when in_stock > 0 then 0 else 1 end, price
The ordering is not just adding 2 order clause, it needs additional case-when something as below to achieve the desired result set
select * from table_name
order by case when in_stock = 0 then 1 else 0 end , price,in_stock desc ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.