2013-07-30 96 views
2

是一個新手SQL用戶:兩次內部加入同一張桌子與聚合函數

我有一個簡單的表,每天存儲一些夜晚的記錄。表:

表:T1

+----+-----+----+-----------+------------+ 
| Id | A | AB | Value | Date | 
+----+-----+----+-----------+------------+ 
| 1 | abc | I | -48936.08 | 2013-06-24 | 
| 2 | def | A | 431266.19 | 2013-06-24 | 
| 3 | xyz | I | -13523.90 | 2013-06-24 | 
| 4 | abc | A | 13523.90 | 2013-06-23 | 
| 5 | xyz | I | -13523.90 | 2013-06-23 | 
| 6 | def | A | 13523.90 | 2013-06-22 | 
| 7 | def | I | -13523.90 | 2013-06-22 | 
+----+-----+----+-----------+------------+ 

我想獲得列的所有值A,AB,價值在A列中的最新日期過濾對AB =我

基本結果應該看起來像:

+----+-----+----+-----------+------------+ 
| Id | A | AB | Value | Date | 
+----+-----+----+-----------+------------+ 
| 1 | abc | I | -48936.08 | 2013-06-24 | 
| 3 | xyz | I | -13523.90 | 2013-06-24 | 
| 7 | def | I | -13523.90 | 2013-06-22 | 
+----+-----+----+-----------+------------+ 

我曾嘗試使用內部連接兩次在同一張表,但未能拿出正確的結果。

任何幫助,將不勝感激。

謝謝:)

回答

3

這將SQLSERVER工作2005+

;WITH a as 
(
SELECT id, A,AB, Value, Date 
, row_number() over (partition by A order by Date desc) rn 
FROM t1 
WHERE AB = 'I' 
) 
SELECT id, A,AB, Value, Date 
FROM a WHERE rn = 1 
+0

Thanks-就是這樣。 – SWKK

3
; WITH x AS (
    SELECT id 
     , a 
     , ab 
     , "value" 
     , "date" 
     , Row_Number() OVER (PARTITION BY a ORDER BY "date" DESC) As row_num 
    FROM your_table 
    WHERE ab = 'I' 
) 
SELECT * 
FROM x 
WHERE row_num = 1 
+0

哦,親愛的,太慢了,被同樣的答案毆打!這裏的網絡禮儀是什麼?我應該刪除我的帖子嗎? – gvee