鉴于下表(原始表),我需要运行一个查询,以便对所有内容进行排序以镜像结果表。我已经尝试过使用ORDER BY这样做,我可以得到前两个要求(按需求排序),但第三个要求是我迷路了。
现在,我的查询如下:
sqlCom.CommandText = "SELECT * FROM Questions WHERE Identifier = @identifier AND Flag <> 'DELETED' ORDER BY Status DESC, Number * 1";
我一直在阅读使用ORDER BY CASE WHEN...THEN...END
,但我没有正确理解语法。我一直遇到语法错误,所以我甚至无法运行它。
ORDER BY要求:
据我所知,ORDER BY CASE
是我想要的,但我似乎无法正确理解语法。提前感谢任何有用的输入。
RAW TABLE
| Flag | Number | Status |
|------------------------|
| a | 1 | open |
| | 5 | open |
| | 3 | closed |
| a | 4 | open |
| a | 2 | closed |
结果表
| Flag | Number | Status |
|------------------------|
| a | 1 | open |
| a | 4 | open |
| | 5 | open |
| | 3 | closed |
| a | 2 | closed |
答案 0 :(得分:3)
SELECT * FROM Questions
WHERE Identifier = @identifier AND Flag <> 'DELETED'
ORDER BY Status DESC, Number,
(case when flag is null then 1 else 0 end) desc, flag
你可以试试这个。
答案 1 :(得分:2)
使用嵌套的CASE
表达式:
SELECT *
FROM Questions
--WHERE Identifier = @identifier AND Flag <> 'DELETED'
ORDER BY
CASE WHEN Status = 'Open' THEN 0 ELSE 1 END,
Number *
CASE
WHEN Status = 'Closed' THEN
CASE
WHEN Flag IS NULL THEN 0
ELSE 1
END
ELSE 1
END,
Number,
CASE WHEN Flag IS NULL THEN 1 ELSE 0 END
我们的想法是将Status = 'Closed'
和FLAG IS NULL
的行直接放在Status = 'Open'
行的下方。然后,最后会排序FLAG IS NOT NULL
和Status = 'Closed'
的行。