我試圖改變這樣的數據:PIVOT SQL數據和填寫空白
ItemID MonthAsInt Month Year InvType Quantity
4643 4 April 2011 Shipment 10
4643 5 May 2011 Shipment 10
4643 7 July 2011 Shipment 10
4643 8 August 2011 Destroy 10
4643 11 November 2011 Shipment 25
4643 12 December 2011 Picking 1
進入這個(基本上,12個月的快照):
February March April May June July August ...
Shipment 0 0 10 10 0 10 0
Picking 0 0 0 0 0 0 0
Destroy ...
我已經搞砸PIVIOT
方法,但我沒有太多運氣。在這一點上,我只有我GETDATE()
和GETDATE() - 12 months
之間需要日期的列表(與下面的查詢檢索):
DECLARE @BeginDate DATETIME
DECLARE @EndDate DATETIME
SET @BeginDate = GETDATE();
SET @EndDate = DATEADD(MONTH, -12, GETDATE());
WITH CTE_DatesTable
AS
(
SELECT @EndDate AS [Date]
UNION ALL
SELECT DATEADD(dd, 1, [date])
FROM CTE_DatesTable
WHERE DATEADD(dd, 1, [date]) <= @BeginDate
)
SELECT DISTINCT DATENAME(MONTH, [date]) + ' '
+ CAST(YEAR([date]) AS VARCHAR(4)) AS MonthYear,
YEAR([date]) AS YearAsInt,
MONTH([Date]) AS MonthAsInt
FROM CTE_DatesTable
ORDER BY YEAR([date]), MONTH([Date])
OPTION (MAXRECURSION 0)
看到查詢在行動here。
我試圖完成什麼?我正朝着正確的方向走嗎?任何幫助,將不勝感激!
什麼也沒有用PIVOT工作? – 2012-02-13 18:17:27
@ subt13,** Me **。我從來沒有用過它,我不知道如何「填補空白」。例如,我需要爲所有未包含在第一個結果集中的月份顯示零。 – 2012-02-13 18:21:30
使用樞軸,就是這麼做的。你可以使用isnull(...,0) – 2012-02-13 18:26:48