2013-07-02 111 views
1

分組我有一個桌面日期:選擇通過ID的

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') 

我需要選擇每個用戶ID/testID組合的最新日期。所以,結果將是

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

這聽起來很簡單,但我無法弄清楚。 SQL Fiddle Here

回答

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

fiddle

+0

偉大,謝謝:) – EvilDr

+0

只是要保持謹慎使用此查詢包含更多列的表 - 既不分組也不聚合的列。 – Strawberry

+0

我已發佈此問題的修訂,並希望得到進一步的幫助! http://stackoverflow.com/questions/17424333/select-max-dates-plus-id-value – EvilDr

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

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

+0

@EvilDr - 沒問題。我只是在你的SQL小提琴上測試這個。 –

+1

Er - shurely shome mishtake – Strawberry

+1

那麼它完全依賴於所有'2'等於20並且所有'1'等於50的事實。如果'2'等於'50',該怎麼辦? – Strawberry

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