SQL - запрос заказа по последней дате, а затем по идентификатору - PullRequest
0 голосов
/ 27 января 2020

У меня есть таблица, которая выглядит примерно так:

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

My 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 ]

2 голосов
/ 27 января 2020

Я подозреваю, что вы хотите:

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

Сначала будут поставлены NotificationTypeID с наибольшим CreatedOn, а затем упорядочены записи с одинаковыми NotificationTypeID по убыванию CreatedOn .

0 голосов
/ 27 января 2020

Вы можете попробовать заказать с помощью кейса

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
...