我有这个简单的SQL Select查询:
SELECT part_number, bin_location FROM list ORDER BY bin_location
这会给我一个这样的结果:
part_number bin_location
Alaska wine A1
German water A2
London whisky A3
German wine A4
London water B1
German wine B2
London whisky B3
German wine C1
London whisky C2
Water Green Wine C3
Pure Water D1
Orange whisky D2
Ireland Moat D3
French wine XX
Italy water XX
Water Green Wine XX
Pure Water XX
Orange whisky XX
Ireland Moat XX
French wine XX
Italy water XX
现在我要做的是按bin_location排序,一旦bin_location等于xx order by part_number。
这是我用来执行此操作的查询:
SELECT part_number,bin_location
FROM list
ORDER BY case when bin_location = 'xx' then part_number end
这是我得到的结果:
part_number bin_location
Alaska wine A1
German water A2
London whisky A3
German wine C1
London water A4
German wine B2
London whisky B3
German wine A4
London whisky C2
Water Green Wine C3
Pure Water D1
Orange whisky D2
Ireland Moat D3
French wine XX
French water XX
Ireland Moat xx
Italy water XX
Orange whisky XX
Pure Water XX
Water Green Wine XX
正如您在xx子句满足后所看到的那样,它将part_number按顺序放置,但在此之前,bin位置不是。
我该如何解决这个问题?
提前致谢。
答案 0 :(得分:2)
我想你想要:
SELECT part_number, bin_location
FROM list
ORDER BY (CASE WHEN bin_location = 'xx' THEN 1 ELSE 2 END), -- put non-XX first
(CASE WHEN bin_location <> 'xx' THEN bin_location END),
part_number;
答案 1 :(得分:1)
我认为不需要CASE
声明。您可以按如下方式查询:
SELECT part_number, bin_location
FROM list
ORDER BY bin_location, part_number;
如果您打算bin_location
不区分大小写(即xx
和XX
应该被视为相似),那么您可以这样做:
SELECT part_number, bin_location
FROM list
ORDER BY UPPER(bin_location), part_number;
希望这有帮助。