2016-06-29 97 views
0

分組我在SQL Server 2012中一個視圖,其中顯示的一些項目的交易如下:獲取的價值總和每月由特定領域

物品交易簡單查看樣品

enter image description here

我需要顯示每月每個項目的總成本總額(數量乘以成本),並顯示如下列的月份:

enter image description here

回答

1

試試這個。

SELECT * FROM (SELECT 
      SUM(Cost) AS Cost, 
      CONVERT(VARCHAR(3), DATENAME(MONTH, DATEADD(MONTH, MONTH(MonthCol), - 1))) MonthCol 
      FROM myTable WHERE YEAR(MonthCol) = 2016 
      GROUP BY MonthCol) AS TP 
    PIVOT (SUM(Cost) FOR MonthCol IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) AS PVTTable 

對於動態查詢月份和

DECLARE @CurrMonth DATE = GETDATE(); 
    DECLARE @CurrYear NVARCHAR(4) = CAST(YEAR(@CurrMonth) AS NVARCHAR(4)) 
    DECLARE @END_MM INT = MONTH(@CurrMonth) --Current Month 
    DECLARE @START_MM INT = 1 --Start Month of Current Year 

    DECLARE @TB_DATE AS TABLE 
    (
     ID INT IDENTITY(1,1), 
     DATE_LIST VARCHAR(12) 
    ) 
    WHILE @START_MM <= @END_MM 
    BEGIN 
     INSERT INTO @TB_DATE (DATE_LIST) VALUES ('['+CONVERT(VARCHAR(3),DATENAME(MONTH, DATEADD(month, @START_MM-1, CAST(@END_MM AS datetime))))+']') 
     SET @[email protected]_MM+1 
    END 

    DECLARE @MM_LIST NVARCHAR(MAX) = (SELECT STUFF((SELECT ',' + DATE_LIST 
         FROM @TB_DATE ORDER BY ID DESC 
         FOR XML PATH('')) ,1,1,'') AS Txt) 

    DECLARE @DynamicPivot AS NVARCHAR(MAX) 
    SET @DynamicPivot = N'SELECT * FROM (SELECT 
     ItemId, 
     ItemName, 
     SUM(TotalCost) AS TotalCost, 
     CONVERT(VARCHAR(3), 
     DATENAME(MONTH, DATEADD(MONTH, MONTH(TransDate), - 1))) TransDate 
     FROM myTable WHERE YEAR(TransDate) = '[email protected]+' 
     GROUP BY TransDate,ItemId,ItemName) AS TP 
PIVOT (SUM(TotalCost) FOR TransDate IN ('[email protected]_LIST+')) AS PVTTable'; 

EXEC sp_executesql @DynamicPivot 
+0

謝謝你這麼多,但如果我想控制多少個月來顯示,爲前:如果我想七月前顯示月,這可能嗎 ? – Morz

+0

是的,我們可以,請在Dynamic Month Query中嘗試我的回答 – taotechnocom

+0

非常感謝。 – Morz