每月最后一天的月度金额和产出

时间:2017-04-13 08:09:09

标签: sql-server sql-server-2014

我有example 1

这样的表格

这里是按天计算的总和。我需要按月加总金额并加入月份最后一天的值,请参阅图片example 2

由于

2 个答案:

答案 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)