使用Dynamic Pivot隐藏具有所有空值的行

时间:2014-07-15 17:55:07

标签: sql sql-server sql-server-2008

我问了一个问题,答案出现了,因为我必须使用Dynamic Pivot Link to Question,我得到了很大的帮助。现在,我试图摆脱所有空值的行,但我不能。

*请注意,当前结果的列标题应为部分01,部分ABC和部分03(如图所示不是0) enter image description here

WHERE SubPart IS NOT NULL/ WHERE  Quantity IS NOT NULL 

但它不起作用(好吧,它仍然查询但是使用空值)

FROM和来自语句之后

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 个答案:

答案 0 :(得分:1)

您需要将where条件添加到内部查询中,该内部查询用作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
'