具有复杂聚合的{s}数据透视查询

时间:2016-05-31 10:58:10

标签: sql sql-server pivot

我在使用数据透视查询(SQL Server)时遇到了一些问题。 任务非常简单:对于一个人,我必须收集一年中每个月的收入统计数据,但每个新月收入都基于previuos incomecurrent 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执行此类查询的方法是什么?

1 个答案:

答案 0 :(得分:1)

也许是这样的? (此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;