You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL Server中实现复杂ORDER BY排序需求

需求说明

需要对customer_updates表执行以下排序操作:

  • 先按每个Cust_Id对应的**最新Last_updated_date**降序排列各组
  • 组内再按Last_updated_date降序排列

常规排序后的表

Update_IDCust_IdField_updatedLast_updated_dateUpdated_by
11223Name2021-11-01 12:23Frodo Baggins
29999address2021-12-02 19:23Legolas
32200phone2021-12-03 23:00Bilbo Baggins
42200Name2022-01-04 02:23Bilbo Baggins
59999phone2022-02-05 12:23Golum
69999address2022-03-06 20:00Sauron
71223address2022-04-07 01:24Gandalf
82200email2022-05-08 12:50Some Urkai
93412email, phone2022-06-08 08:45Golum
101223address2022-07-10 00:23Pippin
113412email, address2022-09-22 16:48Gandalf

预期结果

Update_IDCust_IdField_updatedLast_updated_dateUpdated_by
113412email, address2022-09-22 16:48Gandalf
93412email, phone2022-06-08 08:45Golum
101223address2022-07-10 00:23Pippin
71223address2022-04-07 01:24Gandalf
11223Name2021-11-01 12:23Frodo Baggins
82200email2022-05-08 12:50Some Urkai
42200Name2022-01-04 02:23Bilbo Baggins
32200phone2021-12-03 23:00Bilbo Baggins
69999address2022-03-06 20:00Sauron
59999phone2022-02-05 12:23Golum
29999address2021-12-02 19:23Legolas

解决方案

可以使用窗口函数MAX()计算每个Cust_Id对应的最新更新日期,再基于该值和原日期完成排序:

SELECT 
    Update_ID,
    Cust_Id,
    Field_updated,
    Last_updated_date,
    Updated_by
FROM customer_updates
ORDER BY 
    -- 按客户组的最新更新日期降序排列组
    MAX(Last_updated_date) OVER (PARTITION BY Cust_Id) DESC,
    -- 组内按更新日期降序排列
    Last_updated_date DESC;

思路说明

  1. MAX(Last_updated_date) OVER (PARTITION BY Cust_Id):为每条记录生成其所属Cust_Id的最新更新日期
  2. 优先按该全局最大值降序排序,确保更新时间最近的客户组排在最前
  3. 组内再按Last_updated_date降序,保证组内记录从新到旧排列

内容的提问来源于stack exchange,提问作者Lazytitan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 15:51:55