1

可能重复:
SQL:如何以某种任意方式对查询结果进行排序/排序?

我想订购这样的列(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

汽车是我试图在其上运行多排序的列。

4

4 回答 4

2
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

SQL 小提琴示例

输出:

| CARS | SIZE |
---------------
|    c |    1 |
|    b |    1 |
|    a |    1 |
|    g |    1 |
|    h |    1 |
|    i |    1 |
于 2012-11-02T16:02:37.663 回答
2

你可以使用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

这是一个小提琴:http ://www.sqlfiddle.com/#!3/d26a8/1/0

于 2012-11-02T15:59:53.447 回答
1

尝试这个...

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
于 2012-11-02T16:05:32.500 回答
1

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
于 2012-11-02T15:58:59.990 回答