Versuchen Sie es.
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
für dynamische Abfrage Monat und Jahr
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
Dank Sie so viel, aber was ist, wenn ich zu steuern, wie viele Monate angezeigt werden, zum Beispiel: wenn ich will vor Juli Monate angezeigt werden, Ist das möglich ? – Morz
Ja können wir, bitte versuchen Sie in Dynamic Month Query als meine Antwort – taotechnocom
Vielen Dank. – Morz