选择按ID分组的最新日期

时间:2013-07-02 10:45:18

标签: sql sql-server tsql sql-server-2012

我有一张表格如下:

DECLARE @tmp TABLE
    (
    userID int,
    testID int,
    someDate datetime
    )

在其中我存储日期以及两个ID值,例如

INSERT INTO @tmp (userID, testID, someDate) VALUES (1, 50, '2010-10-01')
INSERT INTO @tmp (userID, testID, someDate) VALUES (1, 50, '2010-11-01')
INSERT INTO @tmp (userID, testID, someDate) VALUES (1, 50, '2010-12-01')
INSERT INTO @tmp (userID, testID, someDate) VALUES (2, 20, '2010-10-01')
INSERT INTO @tmp (userID, testID, someDate) VALUES (2, 20, '2010-11-01')

我需要为每个userID / testID组合选择最新日期。所以,结果将是

userID  testID  someDate
1       50      2010-12-01
2       20      2010-11-01

这听起来很容易,但我无法弄清楚。 SQL Fiddle Here

3 个答案:

答案 0 :(得分:2)

SELECT userID, testID, MAX(someDate)
FROM @tmp
GROUP BY testId,userID;

fiddle

答案 1 :(得分:0)

SELECT userId, testId, MAX(someDate)
FROM @tmp
GROUP BY testId, userId

http://www.sqlfiddle.com/#!6/d41d8/5205

答案 2 :(得分:0)

尝试

SELECT t1.* FROM @tmp t1
INNER JOIN (SELECT userId, MAX(someDate) someDate
            FROM @tmp
            GROUP BY userId) t2
        ON t1.userId = t2.userId
       AND t1.someDate = t2.someDate