2016-06-14 21 views
0

我有以下SQL查詢,顯示給定日期的12個月摘要報告。輸出顯示從1月到12月,無論給定日期。
我想要結果從給定日期的月份開始。從給定月份開始的SQL年總結

如果日期是'2016-05-01'我想要的輸出是這樣

May 16 |June 16| July 16| ........... | Jan 17 | Feb 17 | March 17 | April 17 | 

我怎樣才能做到這一點?
有人可以建議嗎?

SELECT Name,SUM(Amount) AS PremiumTot,TotType, 
sum(case when month(Dates) = 1 then Tot else 0 end) Jan, 
sum(case when month(Dates) = 2 then Tot else 0 end) Feb, 
sum(case when month(Dates) = 3 then Tot else 0 end) March, 
sum(case when month(Dates) = 4 then Tot else 0 end) April, 
sum(case when month(Dates) = 5 then Tot else 0 end) May, 
sum(case when month(Dates) = 6 then Tot else 0 end) June, 
sum(case when month(Dates) = 7 then Tot else 0 end) July, 
sum(case when month(Dates) = 8 then Tot else 0 end) Aug, 
sum(case when month(Dates) = 9 then Tot else 0 end) Sep, 
sum(case when month(Dates) = 10 then Tot else 0 end) Oct, 
sum(case when month(Dates) = 11 then Tot else 0 end) Nov, 
sum(case when month(Dates) = 12 then Tot else 0 end) Dece 

FROM 
(
    SELECT InvoiceMasterID,Dates ,Name,CompanyCommission AS Tot ,0 AS Expences,Amount,1 as TotType 
    FROM CommissionView 

    UNION ALL 

SELECT InvoiceMasterID,Dates,Name, 0 AS Tot ,-AgentCommission AS Expences,Amount,2 as TotType 
    FROM CommissionViewCredit 
) a 
    WHERE Dates between @fromDates AND Datesadd(yy,1,@fromDates) 
    GROUP BY Name,TotType 
+0

要即時重新排序列,您需要使用動態sql並構建sql語句,然後執行它。如果你這樣做,我也可以建議看看PIVOT,因爲那樣你就只需要重新排列最後的列。 – Matt

回答

3

似乎,你想要透視數據。所以,使用PIVOT表!

如果要從給定日期創建動態列,請使用CTE(公用表表達式)!

--declare variables for given date range 
DECLARE @startDate DATE = '2016-05-01' 
DECLARE @endDate DATE = DATEADD(mm,11,@startDate) 
--declare variable to store months as: [month1], [month2], [etc.] 
DECLARE @Months VARCHAR(1000) = '' 
--use cte to create range of dates 
;WITH MyDates AS 
(
    SELECT @startDate AS MyDate 
    UNION ALL 
    SELECT DATEADD(mm,1,MyDate) AS MyDate 
    FROM MyDates 
    WHERE MyDate<@endDate 
) 
SELECT @Months = STUFF((SELECT '],[' + CONVERT(VARCHAR(7), MyDate, 121) 
         FROM MyDates 
         FOR XML PATH('')), 1, 2, '') + ']' 

--PRINT @Months: 
-- prints: [2016-05],[2016-06], ... ,[2017-04] 

DECLARE @qry NVARCHAR(MAX) = '' 

SET @qry = N'SELECT ' + @Months + 
' FROM (' + 
    ' SELECT CONVERT(VARCHAR(7), Dates, 121) AS MyDate, CompanyCommission AS Tot ' + 
    'FROM CommissionView ' + 
') AS DT ' + 
'PIVOT (SUM(Tot) FOR MyDate IN(' + @Months + ')) AS PT' 
EXEC (@qry) 

如需進一步信息,請訪問:
Dynamic PIVOT
Pivots with dynamic columns
CAST and CONVERT

祝你好運!

+0

我只會建議您訂購您的SELECT @Months ='查詢以確保您按日期獲得正確的列順序 – JamieD77

+0

@ JamieD77,由於創建順序,它應該按正確順序排列。 –

+0

@MaciejLos - 非常感謝您的指導 –

相關問題