SQL查询每个ID的最新日期/时间戳记记录

时间:2018-12-09 09:23:11

标签: sql sql-server tsql greatest-n-per-group

请帮助在列表TABLE下方进行排序,

ID NAME DATE TIME STATUS

ID是唯一的,名称,日期,时间,状态在数据库中不断变化。

我需要输出列表,每个用户ID都有最新状态,日期和时间戳记

3 个答案:

答案 0 :(得分:0)

SELECT * FROM table
WHERE C_Time = 
  (SELECT max(C_Time) FROM table t1 WHERE C_Date = 
    (SELECT max(C_Date) FROM table t2 WHERE t1.ID = t2.ID)
  );

这将为您提供每个C_Date的最高C_TimeID值的条目

答案 1 :(得分:0)

怎么样

SELECT T1.*
FROM T T1 INNER JOIN
    (
        SELECT ID,
               CName,
               MAX(CDate) CDate,
               MAX(CTime) CTime
        FROM T
        GROUP BY ID,
                 CName
    ) T2 
ON T1.CDate = T2.CDate 
   AND 
   T1.CTime = T2.CTime 
   AND T1.CName = T2.CName;

哪个会回来

+---------------------+----------+--------+----+-------+
|        CDate        |  CTime   | Status | ID | CName |
+---------------------+----------+--------+----+-------+
| 22/12/2018 00:00:00 | 16:27:57 |      1 |  1 | A     |
| 21/12/2018 00:00:00 | 15:41:13 |      4 |  2 | B     |
| 20/12/2018 00:00:00 | 12:35:27 |      3 |  2 | C     |
| 21/12/2018 00:00:00 | 15:29:46 |      4 |  3 | D     |
+---------------------+----------+--------+----+-------+

OR

SELECT T1.*
FROM T T1 INNER JOIN
    (
        SELECT ID,
               MAX(CDate) CDate,
               MAX(CTime) CTime
        FROM T
        GROUP BY ID
    ) T2 
ON T1.CDate = T2.CDate 
   AND 
   T1.CTime = T2.CTime;

哪个会回来

+---------------------+----------+--------+----+-------+
|        CDate        |  CTime   | Status | ID | CName |
+---------------------+----------+--------+----+-------+
| 22/12/2018 00:00:00 | 16:27:57 |      1 |  1 | A     |
| 21/12/2018 00:00:00 | 15:41:13 |      4 |  2 | B     |
| 21/12/2018 00:00:00 | 15:29:46 |      4 |  3 | D     |
+---------------------+----------+--------+----+-------+

Demo

答案 2 :(得分:0)

我将为此使用窗口函数:

select t.*
from (select t.*,
             row_number() over (partition by id order by date desc, time desc) as seqnum
      from t
     ) t
where seqnum = 1;

或者,如果您有一个表,每个客户一行,那么apply可能是最好的:

select t.*
from customers c cross apply
     (select top (1) t.*
      from t
      where t.id = c.id
      order by date desc, time desc
     ) t;