2014-09-24 68 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