2016-05-31 53 views
0

我有一些数据透视查询(SQL Server)的问题。 的任务很简单:一个人我一定要收集它的收入统计每个月的一年,但每一个新的一个月收入是基于previuos income加上current month income复杂聚合的Sql数据透视查询

只是为了举例。让人不得不每月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

只是一些我的头顶部提示:内部查询使用合适的窗口(?行之间无界前和电流)和划分,并用标签为您的期间1to2,1to3,1to4等然后在您的标签上旋转。如果我晚点晚些时候,我会看看一个完整的解决方案。 –

回答

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

如果有前一年的值,它会影响明年的结果。 – shadeglare

+1

我认为PARTITION BY personid,year(date)ORDER BY [date]应该满足您的要求。 –

+0

谢谢。按预期工作。 – shadeglare