SQL-按最新日期排序,然后按ID排序

时间:2020-01-27 17:00:54

标签: sql sql-order-by

我有一个看起来像这样的表:

NotificationID  NotificationTypeID CreatedOn
5               2                  2020-01-27 10:05:33.147
4               13                 2020-01-24 15:56:04.437
3               3                  2020-01-24 14:16:53.327
2               2                  2020-01-24 14:16:53.327
1               1                  2020-01-22 15:12:38.663

我希望按CreatedOn字段进行排序,然后按如下所示的NotificationTypeID进行排序:

NotificationID  NotificationTypeID CreatedOn
5               2                  2020-01-27 10:05:33.147
2               2                  2020-01-24 14:16:53.327
4               13                 2020-01-24 15:56:04.437
3               3                  2020-01-24 14:16:53.327
1               1                  2020-01-22 15:12:38.663

我的SQL看起来像这样:

SELECT  
    ROW_NUMBER() OVER (PARTITION BY Notification.NotificationTypeID ORDER BY CreatedOn DESC) RowNumber,
    Notification.NotificationID,
    Notification.NotificationTypeID,
    CreatedOn
FROM Notification
ORDER BY RowNumber DESC, CreatedOn DESC

但是它首先给了我最早的价值:

NotificationID  NotificationTypeID CreatedOn
2               2                  2020-01-24 11:34:37.063
5               2                  2020-01-27 10:05:33.147
4               13                 2020-01-24 15:56:04.437
3               3                  2020-01-24 14:16:53.327
1               1                  2020-01-22 15:12:38.663

2 个答案:

答案 0 :(得分:2)

我怀疑您想要

select NotificationID, NotificationTypeID, CreatedOn
from Notification
order by
    max(CreatedOn) over(partition by NotificationTypeID) desc,
    CreatedOn desc

这将首先放置NotificationTypeID最大的CreatedOn,然后通过降序NotificationTypeID对具有相同CreatedOn的记录进行排序。

答案 1 :(得分:0)

您可以尝试按大小写排序

Order by CreatedOn desc, 
case when NotificationTypeID = 2 then 1
     when NotificationTypeID = 13 then 2
     when NotificationTypeID = 3 then 3
     when NotificationTypeID = 1 then 4 End