我有以下SQL查询,显示给定日期的12个月摘要报告。无论给定日期如何,输出显示从1月到12月。我希望结果从给定日期的月份开始。
如果给定日期是'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 :(得分: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