分组内的 SQL 排序

标签 sql sql-server sorting

我需要 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/

相关文章:

php - 将 1 个表列中的文本与另一个表列中的部分字符串匹配

sql - 如何将mysql查询转换为oracle(对3个表使用UPDATE和INNER JOIN 2次)

c# - 从 sql server 获取顶部(开始号,结束号)行

sql-server - 如何在 SQL Server 中创建数据库的数据库图

sql - 除了分组依据之外我还能使用什么?

c++ - 对 vector 中的点进行排序以形成轮廓

javascript - 循环遍历除最后一个值之外的 html 选择列表

sql - SQL有条件地选择不同的聚合

c# - 使用 Array.Sort() 对元素进行排序而不是对第一个元素进行排序

mysql - 如何显示列名和嵌套聚合结果