我有一个数据集(SQL Server 2012)我试图从每个帐号中提取最终的月度总数,并将不同的位置汇总在一起。我需要YYYYMMDD中月末最后一天的最终余额编号。拉入最小值或最大值不会起作用,因为余额可能更高或更低,但它需要Group By功能的聚合。你怎么能参考这个余额?
请参阅下面的示例,目标输出低于
Account# Location Balance YYYYMMDD YYYYMM
1 South $400 20171030 201710
1 South $395 20171031 201710
1 South $402 20171101 201711
1 South $408 20171102 201711
1 North $75 20171030 201710
1 North $80 20171031 201710
1 North $80 20171101 201711
1 North $72 20171102 201711
2 South $5,000 20171030 201710
2 South $5,200 20171031 201710
2 South $5,200 20171101 201711
2 South $5,500 20171102 201711
2 North $2,000 20171030 201710
2 North $1,800 20171031 201710
2 North $1,700 20171101 201711
2 North $1,600 20171102 201711
Account# Balance YYYYMM
1 $475 201710
1 $480 201711
2 $7,000 201710
2 $7,100 201711
谢谢!
答案 0 :(得分:0)
row_number()
是一种典型的方法:
select t.*
from (select account, yyyymm, yyyymmdd, sum(balance) as balance,
row_number() over (partition by account, yyyymm order by yyyymmdd desc) as seqnum
from t
group by account, yyyymm, yyyymmdd
) t
where seqnum = 1;