答案 0 :(得分:1)
试试这个:
SELECT t.amount, t.dt, CASE WHEN month_cnt = rn THEN s ELSE NULL END AS month_s FROM (
select your_table.*,
sum(amount) over(partition by year(dt), month(dt) ) s,
count(*) over(partition by year(dt), month(dt)) month_cnt,
ROW_NUMBER() over(partition by year(dt), month(dt) order by dt) rn
from your_table
)t
order by dt
答案 1 :(得分:0)
这样的事情怎么样?
create table #test
(
amount int,
trans date
)
insert into #test
SELECT
30, '2017-02-15'
UNION
SELECT
20, '2017-02-18'
UNION
SELECT
25, '2017-02-25'
UNION
SELECT
10, '2017-03-22'
UNION
SELECT
80, '2017-03-23'
UNION
SELECT
54, '2017-04-11'
SELECT
DATEPART(month, trans) month, SUM(amount) Sum
FROM
#test
GROUP BY
DATEPART(month, trans)