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

Total de filas y columnas en pivote dinámico

TABLA DE MUESTRA

SELECT * INTO #tblStock
FROM
(
SELECT 'A' PartCode,  10 StockQty, 'WHs-A' Location
UNION ALL
SELECT 'B',   22,  'WHs-A'
UNION ALL
SELECT 'A',   1,   'WHs-B'
UNION ALL
SELECT 'C',   20,  'WHs-A'
UNION ALL
SELECT 'D',   39,  'WHs-F'
UNION ALL
SELECT 'E',   3,   'WHs-D'
UNION ALL
SELECT 'F',   7,   'WHs-A'
UNION ALL
SELECT 'A',   9,   'WHs-C'
UNION ALL
SELECT 'D',   2,   'WHs-A'
UNION ALL
SELECT 'F',   54,  'WHs-E'
)TAB

Obtenga las columnas para el pivote dinámico y reemplace NULL con zero

DECLARE @cols NVARCHAR (MAX)

SELECT @cols = COALESCE (@cols + ',[' + Location + ']', '[' + Location + ']')
               FROM (SELECT DISTINCT Location FROM #tblStock) PV 
               ORDER BY Location 
-- Since we need Total in last column, we append it at last
SELECT @cols += ',[Total]'


--Varible to replace NULL with zero
DECLARE @NulltoZeroCols NVARCHAR (MAX)

SELECT @NullToZeroCols = SUBSTRING((SELECT ',ISNULL(['+Location+'],0) AS ['+Location+']' 
FROM (SELECT DISTINCT Location FROM #tblStock)TAB  
ORDER BY Location FOR XML PATH('')),2,8000) 

SELECT @NullToZeroCols += ',ISNULL([Total],0) AS [Total]'

Puedes usar CUBE para encontrar el total de filas y columnas y reemplazar NULL con Total para las filas generadas desde CUBE .

DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT PartCode,' + @NulltoZeroCols + ' FROM 
             (
                 SELECT 
                 ISNULL(CAST(PartCode AS VARCHAR(30)),''Total'')PartCode, 
                 SUM(StockQty)StockQty , 
                 ISNULL(Location,''Total'')Location              
                 FROM #tblStock
                 GROUP BY Location,PartCode
                 WITH CUBE
             ) x
             PIVOT 
             (
                 MIN(StockQty)
                 FOR Location IN (' + @cols + ')
            ) p
            ORDER BY CASE WHEN (PartCode=''Total'') THEN 1 ELSE 0 END,PartCode' 

EXEC SP_EXECUTESQL @query

RESULTADO

NOTA:si desea NULL en lugar de zero como valores, use @cols en lugar de @NulltoZeroCols en código pivote dinámico

EDITAR:

1. Mostrar solo el total de filas

  • No use el código SELECT @cols += ',[Total]' y SELECT @NullToZeroCols += ',ISNULL([Total],0) AS [Total]' .
  • Usar ROLLUP en lugar de CUBE .

2. Mostrar solo el total de la columna

  • Utilice el código SELECT @cols += ',[Total]' y SELECT @NullToZeroCols += ',ISNULL([Total],0) AS [Total]' .
  • Usar ROLLUP en lugar de CUBE .
  • Cambiar GROUP BY Location,PartCode a GROUP BY PartCode,Location .
  • En lugar de ORDER BY CASE WHEN (PartCode=''Total'') THEN 1 ELSE 0 END,PartCode , use WHERE PartCode<>''TOTAL'' ORDER BY PartCode .

ACTUALIZAR:Para traer PartName para OP

Estoy actualizando la siguiente consulta para agregar PartName con resultado Desde PartName agregará resultados adicionales con CUBE y para evitar confusiones en AND o OR condiciones, es mejor unir el resultado pivotado con DISTINCT valores en su tabla de origen.

DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT P.PartCode,T.PartName,' + @NulltoZeroCols + ' FROM 
             (                
                 SELECT 
                 ISNULL(CAST(PartCode AS VARCHAR(30)),''Total'')PartCode, 
                 SUM(StockQty)StockQty , 
                 ISNULL(Location,''Total'')Location              
                 FROM #tblStock
                 GROUP BY Location,PartCode
                 WITH CUBE                   
             ) x
             PIVOT 
             (
                 MIN(StockQty)
                 FOR Location IN (' + @cols + ')
            ) p
            LEFT JOIN
            (  
                SELECT DISTINCT PartCode,PartName
                FROM #tblStock  
            )T
            ON P.PartCode=T.PartCode
            ORDER BY CASE WHEN (P.PartCode=''Total'') THEN 1 ELSE 0 END,P.PartCode' 

EXEC SP_EXECUTESQL @query