Sql 具有复杂聚合的数据透视查询

Sql pivot query with complex aggregation

我在数据透视查询(SQL 服务器)方面遇到了一些问题。 任务很简单:对于一个人,我必须收集一年中每个月的收入统计数据,但每个新月的收入都是基于 previuos income 加上 current month income

举个例子。假设一个人每个月有3k的薪水(为了简单起见,它是一个常数)那么查询结果应该是这样的:

Year | Jan | Feb | ... | Dec
2016 | 3k  | 6k  | ... | 36k
2015 | 3k  | 6k  | ... | 36k
...

一个伪 SQL 查询是:

select * from (
    select 
        year(date) as year,
        month(date) as month
        salary,
    from income
    where personId = 'some id'
) as tmp
pivot (
    sum(salary),
    for month in ([1], [1..2], [1..3], ...)
) as pvt

问题是 SQL 中没有 [1..2] 表达式。 使用标准 SQL 执行此类查询的方法是什么?

也许是这样的? (此 OVER 适用于 2008 R2 及之后的版本)

create table #income (
    personid int,
    salary int,
    [date] date
)

insert into #income 
(personid,salary,[date])
values
(1,3000,'2016-01-31'),
(1,3000,'2016-02-29'),
(1,3000,'2016-03-31'),
(1,3000,'2016-04-30'),
(1,3000,'2016-05-31');

select * from (
    select 
        year(date) as year,
        month(date) as month,
        SUM(salary) OVER ( PARTITION BY personid ORDER BY [date]) salary
    from income
    where personId = 1
) as tmp
pivot (
    sum(salary)
    for month in ([1], [2], [3],[4],[5])
) as pvt;

drop table #income;