我需要 SQL (MSSQL) 方面的帮助,其中我按多个 bool 类型进行排序以便对结果进行分组,但还需要按每个类型分组中的日期字段进行排序。
下面的 SQL 看起来工作正常:
Select * from staff ORDER BY admin DESC, hr DESC, sales DESC, it DESC, updated DESC
诀窍在于,某些记录选择了不止一种类型,然后输出就会变得困惑。我只需要在一个分组中显示员工,但他们应该在每个分组中按更新的 DESC 排序。
这是我得到的输出:
Name updated admin hr sales it
-------------------------------------------
fred 2012/04/01 true true
bill 2011/10/01 true true
joe 2012/04/01 true
sam 2012/03/01 true
jo 2012/02/01 true
beth 2012/03/01 true
mary 2012/02/01 true
harry 2011/02/01 true true
gary 2012/04/01 true
bruce 2012/04/01 true
这是我需要的输出
Name updated admin hr sales it
-------------------------------------------
fred 2012/04/01 true true
joe 2012/04/01 true
sam 2012/03/01 true
jo 2012/02/01 true
bill 2011/10/01 true true
beth 2012/03/01 true
mary 2012/02/01 true
gary 2012/04/01 true
harry 2011/02/01 true true
bruce 2012/04/01 true
希望这是有道理的。
最佳答案
您可以在 order by 子句中使用 case 表达式进行条件排序。
SELECT *
FROM staff
ORDER BY
admin DESC,
CASE admin WHEN 'true' THEN updated END DESC,
hr DESC,
CASE hr WHEN 'true' THEN updated END DESC,
sales DESC,
CASE sales WHEN 'true' THEN updated END DESC,
it DESC,
updated DESC
关于分组内的 SQL 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10314399/