2014-07-15 66 views
0

我問了一個問題,答案出現了,因爲我必須使用Dynamic Pivot Link to Question,我得到了很大的幫助。現在,我試圖擺脫所有空值的行,但我不能。使用Dynamic Pivot隱藏所有空值的行

*請注意,目前的結果列標題應該是01部分,第一部分ABC,和第03(如圖所示不爲0) enter image description here

WHERE SubPart IS NOT NULL/ WHERE Quantity IS NOT NULL 

,但它不工作(當然,它仍然查詢但空值)

後,從又從聲明

DECLARE @columns NVARCHAR(MAX)  
     ,@sql NVARCHAR(MAX) 

SET @columns = N'' 
--Get column names for entire pivoting 
SELECT @columns += N', ' + QUOTENAME(SpreadCol) 
    FROM (select distinct Part_Number as SpreadCol 
     from test 
     ) AS T 
--select @columns 
SET @sql = N' 
SELECT SubPart, ' + STUFF(@columns, 1, 2, '') + ' 
FROM 
(select SubPart , Part_Number as SpreadCol , Quantity 
from test) as D 
PIVOT 
(
    sum(Quantity) FOR SpreadCol IN (' 
    + STUFF(REPLACE(@columns, ', [', ',['), 1, 1, '') 
    + ') 
) AS Pivot1 
' 
--select @sql 

EXEC sp_executesql @sql 

回答

1

您需要添加的地方CON dition到用作源piovot和列清單查詢

DECLARE @columns NVARCHAR(MAX)  
     ,@sql NVARCHAR(MAX) 

SET @columns = N'' 
--Get column names for entire pivoting 
SELECT @columns += N', ' + QUOTENAME(SpreadCol) 
    FROM (select distinct Part_Number as SpreadCol 
     from test WHERE Quantity IS NOT NULL 
     ) AS T 
--select @columns 
SET @sql = N' 
SELECT SubPart, ' + STUFF(@columns, 1, 2, '') + ' 
FROM 
(select SubPart , Part_Number as SpreadCol , Quantity 
from test WHERE Quantity IS NOT NULL ) as D 
PIVOT 
(
    sum(Quantity) FOR SpreadCol IN (' 
    + STUFF(REPLACE(@columns, ', [', ',['), 1, 1, '') 
    + ') 
) AS Pivot1 
' 
+0

我曾嘗試把WHERE數量內部查詢不爲空,因爲你沒有,但空值還是回到 – user2103670

+0

我測試了 - 如果我使用該程序Navicat然後顯示空,但我使用SQL小提琴,然後它不顯示。謝謝 - 我想我有它的工作,但沒有意識到它 – user2103670