sql >> Base de Datos >  >> RDS >> Sqlserver

Ocultar fila con todos los valores nulos usando Dynamic Pivot

Debe agregar la condición where a la consulta interna que se utiliza como fuente para piovot y la consulta de la lista de columnas

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
'