我的表格如下
T1 (date int, dateYearMonth int, userID int, shopID int, amount numeric(18,2))
示例数据:
(20151212, 201512, 1, 1, 50.00),
(20151213, 201512, 1, 1, 30.00),
(20160110, 201601, 1, 1, 13.00)
我想为用户返回每个月的累计金额, 我的疑问是:
select t.dateYearMonth, t.userID,
sum(t.sum_amount) over
(partition by t.userID order by t.dateYearMonth
rows between unbounded preceding and current row)
from (select dateYearMonth, userID, sum(amount) as sum_amount FROM T1
group by dateYearMonth, userID) t
有更优化的方法吗? 输出预期
(201512, 1, 1, 80.00), (201601, 1, 1, 93.00)
答案 0 :(得分:0)
您可以使用:
SELECT DISTINCT dateYearMonth, userID
,total = SUM(amount) OVER(PARTITION BY userID ORDER BY dateYearMonth)
FROM T1;
的 LiveDemo
强>
答案 1 :(得分:0)