2014-09-24 60 views
1

我使用SQL Server 2012的如何分組並選擇SQL Server中的最新數據記錄?

我查詢的結果是這樣的:

enter image description here

我如何只max(tnxdate)sum(total)記錄?

像這樣:

total actbucket tnxbucket 
-------------------------------- 
4  18+ 7-12 m 

我嘗試這樣做:

select 
    sum(id), tnxbucket, actbucket 
from 
    (select 
     *, 
     rn = row_number()over(partition by id order by tnxdate desc) from t 
    ) x 
where 
    x.rn = 1 
group by 
    tnxbucket, actbucket 

,但它給了我這樣的

total actbucket tnxbucket 
------------------------------ 
3 18+ 18+ 
1 18+ 7-12 

我想tnxbucket,actbucket即與最大tnxdate

謝謝小號!

+0

感謝@marc爲編輯..你可以與查詢幫助嗎? – user262503 2014-09-24 09:12:58

+0

日期'20131031'來自您想要的輸出嗎?這是一個錯字嗎? – Tanner 2014-09-24 09:13:19

+0

抱歉打字@Tanner – user262503 2014-09-24 09:13:53

回答

1

試試這個

SELECT t1.total, t1.tnxdate, t2.actbucket, t2.tnxbucket 
FROM (SELECT id, SUM(total) as total, MAX(tnxdate) as tnxdate 
     FROM table 
     GROUP BY id) t1 
     LEFT JOIN table t2 ON t1.id=t2.id AND t1.tnxdate = t2.tnxdate 
1

試試這個:

;WITH cte as 
(
    SELECT 
    max(tnxdate) over (partition by id) mx, 
    sum(total) over (partition by id) total, 
    actbucket, 
    tnxbucket 
    FROM t 
) 
SELECT TOP 1 
    total, 
    actbucket, 
    tnxbucket 
FROM cte 
ORDER BY 
    mx desc, 
    tnxbucket desc