按降序排列,然后继续使用同一组

时间:2018-10-15 12:09:51

标签: sql-server group-by sql-order-by

我希望记录按DATE降序排列,并继续使用相同的组,即,此处的最大日期为2018-10-25 00:00:00.000,则接下来的3条记录应为REC = 5

REC DATE
===========================
1   2018-01-02 00:00:00.000
1   2018-01-03 00:00:00.000
1   2018-01-04 00:00:00.000
2   2018-06-01 00:00:00.000
2   2018-06-02 00:00:00.000
3   2018-03-01 00:00:00.000
3   2018-05-02 00:00:00.000
3   2018-01-03 00:00:00.000
3   2018-08-04 00:00:00.000
3   2018-10-05 00:00:00.000
4   2018-10-06 00:00:00.000
5   2018-10-25 00:00:00.000
5   2018-05-03 00:00:00.000
5   2018-09-09 00:00:00.000

这是我尝试过的但没有成功。

SELECT t1.REC, t1.DATE
FROM TEMP AS t1
INNER JOIN (SELECT REC, MAX(DATE) AS MaxDate
            FROM TEMP
            GROUP BY REC) AS t2
ON (t1.REC = t2.REC AND t1.DATE = t2.MaxDate)

预期结果应该是这样的:

REC DATE
===============================
5   2018-10-25 00:00:00.000
    ..........{Remaining dates of `REC` 5}
4   2018-10-06 00:00:00.000
    ..........{Remaining dates of `REC` 4}
3   2018-10-05 00:00:00.000
    ..........{Remaining dates of `REC` 3}
2   2018-06-02 00:00:00.000
    ..........{Remaining dates of `REC` 2}
1   2018-01-04 00:00:00.000
    ..........{Remaining dates of `REC` 1}

1 个答案:

答案 0 :(得分:2)

max_date是每个REC的最大日期

SELECT  *, max_date = MAX(DATE) OVER (PARTITION BY REC)
FROM    yourtable
ORDER BY max_date DESC, DATE DESC