[英]how do I sort a presto sql output in a custom order?
I have a table with a column for hierarchy(nation, state, county) and prizes(gold, silver, bronze).我有一张桌子,上面有一个等级列(国家、州、县)和奖品(金、银、铜)。 I need to order it this way我需要这样订购
hierarchy等级制度 | prize奖 |
---|---|
nation国家 | gold金子 |
nation国家 | silver银 |
nation国家 | bronze青铜 |
state状态 | gold金子 |
state状态 | silver银 |
state状态 | bronze青铜 |
county县 | gold金子 |
county县 | silver银 |
county县 | bronze青铜 |
Order By Asc or Desc does not achieve this.按 Asc 或 Desc 排序不能实现这一点。 Is there a way to customize a Order by clause?有没有办法自定义 Order by 子句?
Use CASE in the ORDER BY :在ORDER BY中使用CASE :
SELECT hierarchy, prize
FROM table_name
ORDER BY
CASE hierarchy
WHEN 'nation' THEN 1
WHEN 'state' THEN 2
WHEN 'county' THEN 3
ELSE 4 END,
CASE prize
WHEN 'gold' THEN 1
WHEN 'silver' THEN 2
WHEN 'bronze' THEN 3
ELSE 4 END
Use case
statement to map from value to order for order by clause:使用case
语句将值映射到 order by 子句:
-- sample data
WITH dataset (hierarchy, prize) AS (
values ('nation', 'gold'),
('nation', 'silver'),
('nation', 'bronze'),
('county', 'silver'),
('county', 'bronze'),
('state', 'gold'),
('state', 'silver'),
('state', 'bronze'),
('county', 'gold')
)
-- query
select *
from dataset
order by
case
hierarchy
when 'nation' then 1
when 'state' then 2
when 'county' then 3
else 999
end,
case
prize
when 'gold' then 1
when 'silver' then 2
when 'bronze' then 3
else 999
end
Output:输出:
hierarchy等级制度 | prize奖 |
---|---|
nation国家 | gold金子 |
nation国家 | silver银 |
nation国家 | bronze青铜 |
state状态 | gold金子 |
state状态 | silver银 |
state状态 | bronze青铜 |
county县 | gold金子 |
county县 | silver银 |
county县 | bronze青铜 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.