根据最新日期和每个用户获取最新的sql行

时间:2013-11-10 21:32:39

标签: sql

我有下表:

RowId, UserId, Date
1, 1, 1/1/01
2, 1, 2/1/01
3, 2, 5/1/01
4, 1, 3/1/01
5, 2, 9/1/01

我希望根据日期和每UserId获取最新记录,但作为以下查询的一部分(由于我无法更改此查询的原因,因为这是由工具自动生成但我可以写传递以AND开头的任何东西......):

SELECT RowId, UserId, Date
FROM MyTable
WHERE 1 = 1
AND ( 

// everything which needs to be done goes here . . .

)

我尝试了similar query,但收到错误:

  

当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。

编辑:数据库是Sql Server 2008

4 个答案:

答案 0 :(得分:3)

您可以使用NOT EXISTS条件:

SELECT RowId, UserId, Date
FROM MyTable
WHERE 1 = 1
AND NOT EXISTS (
  SELECT *
  FROM MyTable AS t
  WHERE t.UserId = MyTable.UserId
    AND t.Date > MyTable.Date
)
;

请注意,如果用户具有多个具有相同最新Date值的行,则查询将返回所有此类条目。如有必要,您可以稍微修改子查询的条件,以确保只返回一行:

  WHERE t.UserId = MyTable.UserId
    AND (t.Date > MyTable.Date
      OR t.Date = MyTable.Date AND t.RowId > MyTable.RowId
    )

根据上述条件,如果同一用户存在两个或多个具有相同Date的行,则将返回值RowId更大的行。

答案 1 :(得分:1)

尝试:

SELECT RowId, UserId, Date
FROM MyTable
WHERE 1 = 1
AND EXISTS
(SELECT 1
 FROM (SELECT UserId, MAX(Date) MaxDate
       FROM MyTable
       GROUP BY UserId) m
 WHERE m.UserId = MyTable.UserId and m.MaxDate = MyTable.Date)

SQLFiddle here

答案 2 :(得分:1)

假设您能够修改AND子句中的任何内容,如果您使用的是TSQL,则可以执行此类查询

SELECT RowId, UserId, [Date]
FROM @myTable
WHERE 1 = 1
AND ( 
    RowId IN (
            SELECT D.RowId
            FROM (
                SELECT DISTINCT MAX(RowId) AS RowId, UserId, MAX([Date]) AS [Date]
                FROM @myTable
                GROUP BY UserId
        ) AS D
    )
)

答案 3 :(得分:1)

假设RowID是一个标识列:

SELECT t1.RowId, t1.UserId, t1.Date
FROM MyTable t1
WHERE 1 = 1
AND t1.RowID IN ( 

    SELECT TOP 1 t2.RowID 
    FROM MyTable t2
    WHERE  t1.UserId = t2.UserId
    AND    t2.Date = (SELECT MAX(t3.Date) FROM MyTable t3
                      WHERE t2.UserID = t3.UserId)

)

Demo