Select MAX dates plus ID value

瘦欲@ 提交于 2019-12-10 10:04:47

问题


Please consider the following table...

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

...containing the following values:

INSERT INTO @tmp (ID, userID, testID, someDate) VALUES (1, 1, 50, '2010-10-01')
INSERT INTO @tmp (ID, userID, testID, someDate) VALUES (2, 1, 50, '2010-11-01')
INSERT INTO @tmp (ID, userID, testID, someDate) VALUES (3, 1, 50, '2010-12-01')
INSERT INTO @tmp (ID, userID, testID, someDate) VALUES (4, 2, 20, '2010-10-01')
INSERT INTO @tmp (ID, userID, testID, someDate) VALUES (5, 2, 30, '2010-11-01')
INSERT INTO @tmp (ID, userID, testID, someDate) VALUES (6, 2, 20, '2012-11-01')

I need to retrieve the maximum date for each userID/testID combination of values, and also the accompanying ID value. The results should be:

ID   userID  testID  someDate
-------------------------------
3    1       50      2010-12-01
5    2       30      2010-11-01
6    2       20      2012-11-01

When I try the following query, the result set becomes incorrect and all rows are shown. I cannot omit ID from the GROUP BY clause because it causes and error. Can anyone help please? It seems long-winded to join the table to itself to get these values.

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

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


回答1:


Please try:

select * from (
    select 
        *, 
        ROW_NUMBER() over (partition by userID, testID order by SomeDate desc) Rnum 
    From @tmp
)x where Rnum=1


来源:https://stackoverflow.com/questions/17424333/select-max-dates-plus-id-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!