以前,我的SQL代码看起来像这样,工作得很好(它选择符合条件的所有行,然后按column_5排序,或者更确切地说是第五个字段,然后是column_6)
SELECT *
FROM table
WHERE column_2="blah" AND column_4=34
ORDER BY column_5,column_6
但是,我想要特定的结果在顶部,所以我使用CASE命令,但是当我这样做时,我不能再将其余的结果排序超过1列。例如,以下代码将起作用:
SELECT *
FROM table
WHERE column_2="blah" AND column_4=34
ORDER BY CASE WHEN column_3= 'blah' THEN '1'
ELSE column_4 end
但这不起作用=>
SELECT *
FROM table
WHERE column_2="blah" AND column_4=34
ORDER BY CASE WHEN column_3= 'blah' THEN '1'
ELSE column_4, column_2 end
我在column_2
周围的逗号附近收到语法错误。
我执行CASE命令后,我无法按多列排序。有谁知道我做错了什么以及如何解决它?
答案 0 :(得分:1)
SELECT *
FROM your_table
ORDER BY CASE WHEN column_3 = 'blah'
THEN 1
ELSE 2
END,
column_4,
column_2
答案 1 :(得分:1)
SELECT *
FROM table
WHERE column_2 = 'blah' AND column_4 = 34
ORDER BY
CASE WHEN column_3 = 'blah'
THEN column_5
ELSE column_6
END,
column_4, column_2
;