我想订购这样的列(DESC 值):c、b、a。但是在 DESC 的最后,我想显示值 g,h,i (如果存在) 。我需要对子查询的列进行联合吗?
这是到目前为止的 SQL 脚本:
SELECT cars,size from car_table
GROUP BY cars, size
ORDER BY cars DESC,size ASC
汽车是我试图在其上运行多排序的列。
我想订购这样的列(DESC 值):c、b、a。但是在 DESC 的最后,我想显示值 g,h,i (如果存在) 。我需要对子查询的列进行联合吗?
这是到目前为止的 SQL 脚本:
SELECT cars,size from car_table
GROUP BY cars, size
ORDER BY cars DESC,size ASC
汽车是我试图在其上运行多排序的列。
select cars, size
from car_table
group by cars, size
order by
case
when cars in ('a', 'b', 'c') then cars
else '1'
end desc,
case
when cars in ('g', 'h', 'i') then cars
else '1'
end
输出:
| CARS | SIZE |
---------------
| c | 1 |
| b | 1 |
| a | 1 |
| g | 1 |
| h | 1 |
| i | 1 |
你可以使用CASE
:
SELECT cars,size
from cars_table
GROUP BY cars, size
ORDER BY CASE WHEN cars in ('g','h','i') THEN 1 ELSE 0 END ASC
, cars DESC
, size ASC
尝试这个...
SELECT cars,size
FROM (
SELECT cars,size, CASE SUBSTRING(cars,1,1)
WHEN 'g' THEN '_z'
WHEN 'h' THEN '_y'
WHEN 'i' THEN '_x'
ELSE '' END + cars AS order_cars
FROM car_table
GROUP BY cars,size
) A
ORDER BY order_cars DESC,size ASC
UNION + Subquery 将是我的选择。
SELECT cars, size
FROM
(
SELECT 1 OrderNumber, cars, size from car_table
GROUP BY cars, size
WHERE cars not in ('g','h','i')
UNION ALL
SELECT 2, cars, size from car_table
GROUP BY cars, size
WHERE cars in ('g','h','i')
) aSubQuery
ORDER BY OrderNumber ASC, cars DESC, size ASC