2017-04-13 58 views

回答

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 
+0

非常感謝你!這是我需要的 – Valer

+0

不客氣,如果這是你的問題的答案,請接受它 –

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) 
相關問題