2016-05-12 16 views
-2

enter image description here如何從下表

得到YearNum由MonthNum列和總,集團從上面的表格,我怎麼樣了獲得總每年在不同的列組由monthnum的,我的意思是MonthNum ,TotalIn2013,TotalIn2014,TotalIn2015

輸出應該像第二個表:

enter image description here

+0

'TotalIn2013'指於2013年所有月份的總和? – Wanderer

+0

不,月份組編號爲 – Rajesh

+1

只需爲您的預期外出增加一個樣本以便更好地理解 – Wanderer

回答

0
select id,monthnum, case when (yearnum = 2013) then sum(total) as [totalIn2013] 
when (yearnum = 2014) then sum(total) as [totalIn2014] 
when (yearnum = 2015) then sum(total) as [totalIn2015] from tablename 
end 
group by id,monthnum 
0

從你考慮這個[R樣品:

DECLARE @t TABLE 
(
    YearNum INT 
, MonthNum INT 
, Total BIGINT 
) 

INSERT INTO @t (YearNum, MonthNum, Total) 
VALUES (2013, 11, 15100) 
, (2014, 11, 117100) 
, (2014, 1, 64000) 
, (2014, 2, 59600) 
, (2015, 1, 224150) 
, (2015, 2, 191660); 

使用旋轉功能,以達到你所需要的:

SELECT * 
FROM @t 
PIVOT (
    SUM(Total) 
    FOR YearNum IN ([2013], [2014], [2015]) 
) p 
ORDER BY MonthNum 

如果你想顯示年是動態的,你需要拿出動態SQL,遞歸CTE或一些聰明的適用。

0
SELECT Id, 
     MonthNum, 
     CASE WHEN (YearNum = 2013) THEN SUM(Total) END AS Total2013 
     CASE WHEN (YearNum = 2014) THEN SUM(Total) END AS Total2014 
     CASE WHEN (YearNum = 2015) THEN SUM(Total) END AS Total2015 
FROM TABLE  
GROUP BY Id, MonthNum 
0

您也可以通過動態SQL查詢來實現此目的。

查詢

declare @sql as varchar(max); 

select @sql = 'select MonthNum,' 
     + stuff(
      (
       select distinct ',sum(case YearNum when ' 
       + cast(Yearnum as varchar(4)) 
       + ' then Total else 0 end) as TotalIn' 
       + cast(Yearnum as varchar(4)) 
    from your_table_name 
    for xml path('') 
), 1,1, ''); 

select @sql += ' from table_1 group by MonthNum;'; 

exec(@sql);