DB2使用日期和时间显示用户的最新行记录

时间:2014-08-12 19:51:18

标签: mysql sql database db2 squirrel-sql

我有来自3个用户的100条记录。我想显示每个用户的最新记录。我有以下查询:

SELECT *  
FROM Mytable  
WHERE Dateabc = CURRENT DATE 
AND timeabc =  
(
  SELECT MAX(timeabc)
  FROM Mytable
)

它返回每个人的最新记录,我需要它来返回每个用户的最新记录。

3 个答案:

答案 0 :(得分:0)

我假设你桌子的某个地方有一个用户ID ...

  select userID, max(timeabc) from mytable group by userID

答案 1 :(得分:0)

该解决方案是否应同时支持DB2和mysql?

SELECT * FROM Mytable as x
WHERE Dateabc = CURRENT_DATE 
  AND timeabc = (SELECT MAX( timeabc ) FROM Mytable as y where x.user = y.user)

如果只有DB2存在更有效的解决方案:

SELECT * from (
    SELECT x.*, row_number() over (partition by user order by timeabc desc) as rn 
    FROM Mytable as x
)
WHERE rn = 1

答案 2 :(得分:0)

SELECT *
FROM Mytable as a
WHERE Dateabc = CURRENT_DATE 
AND timeabc =
(
    SELECT MAX( timeabc )
    FROM Mytable as b 
    WHERE a.uId = b.uId
)