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

Række- og kolonnetotal i dynamisk pivot

EKSEMPELTABEL

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

Hent kolonnerne til dynamisk pivotering og erstat NULL med 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]'

Du kan bruge CUBE for at finde række- og kolonnetotal og erstatte NULL med Total for rækkerne genereret fra 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

RESULTAT

BEMÆRK:Hvis du vil have NULL i stedet for zero som værdier, brug @cols i stedet for @NulltoZeroCols i dynamisk pivotkode

REDIGERING:

1. Vis kun rækketotal

  • Brug ikke koden SELECT @cols += ',[Total]' og SELECT @NullToZeroCols += ',ISNULL([Total],0) AS [Total]' .
  • Brug ROLLUP i stedet for CUBE .

2. Vis kun kolonnetotal

  • Brug koden SELECT @cols += ',[Total]' og SELECT @NullToZeroCols += ',ISNULL([Total],0) AS [Total]' .
  • Brug ROLLUP i stedet for CUBE .
  • Skift GROUP BY Location,PartCode til GROUP BY PartCode,Location .
  • I stedet for ORDER BY CASE WHEN (PartCode=''Total'') THEN 1 ELSE 0 END,PartCode , brug WHERE PartCode<>''TOTAL'' ORDER BY PartCode .

OPDATERING:For at bringe PartName for OP

Jeg opdaterer nedenstående forespørgsel for at tilføje PartName med resultat. Siden PartName vil tilføje ekstra resultater med CUBE og for at undgå forvirring i AND eller OR forhold, er det bedre at forbinde det pivoterede resultat med DISTINCT værdier i din kildetabel.

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



  1. Bizart ydeevneproblem:Almindelige tabeludtryk i inline brugerdefineret funktion

  2. Simpel Oracle-forespørgsel:literal svarer ikke til formatstreng

  3. Valg af rækker, hvor de første n-tegn er ens (MySQL)

  4. DatabaseError:værdien er for lang til at typetegn varierer (100)