Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Totale riga e colonna in pivot dinamico

TABELLA ESEMPIO

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

Ottieni le colonne per il pivot dinamico e sostituisci 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]'

Puoi usare CUBE per trovare il totale di righe e colonne e sostituire NULL con Total per le righe generate da 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

RISULTATO

NOTA:se vuoi NULL invece di zero come valori, usa @cols invece di @NulltoZeroCols nel codice pivot dinamico

MODIFICA :

1. Mostra solo il totale delle righe

  • Non utilizzare il codice SELECT @cols += ',[Total]' e SELECT @NullToZeroCols += ',ISNULL([Total],0) AS [Total]' .
  • Usa ROLLUP invece di CUBE .

2. Mostra solo il totale della colonna

  • Utilizza il codice SELECT @cols += ',[Total]' e SELECT @NullToZeroCols += ',ISNULL([Total],0) AS [Total]' .
  • Usa ROLLUP invece di CUBE .
  • Cambia GROUP BY Location,PartCode a GROUP BY PartCode,Location .
  • Invece di ORDER BY CASE WHEN (PartCode=''Total'') THEN 1 ELSE 0 END,PartCode , usa WHERE PartCode<>''TOTAL'' ORDER BY PartCode .

AGGIORNAMENTO:per portare PartName per OP

Sto aggiornando la query seguente per aggiungere PartName con risultato. Da PartName aggiungerà risultati extra con CUBE e per evitare confusione in AND o OR condizioni, è meglio unire il risultato pivot con il DISTINCT valori nella tabella di origine.

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