2016-05-31 88 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