将总列和行添加到sql server pivot

时间:2014-08-06 21:45:56

标签: sql sql-server-2008

我有一个我相信正在工作的数据透视表。我想在此透视图中添加总列和总行。这是数据透视表的代码......

 SELECT Month, 
        [N] AS Expected, 
        [R] AS Requested, 
        [T] AS Tires, 
        [U] AS Unexpected, 
        [D] AS Damage
 FROM (
    SELECT CustomerNo, 
           DATEPART(mm,InvoiceDate) AS Month, 
           [Type], 
           SUM(Total) AS Cost 
     FROM  tbl_PM_History 
     WHERE (InvoiceDate >= @Start) 
       AND (InvoiceDate <= @End) 
       AND (CustomerNo = @Cust) 
     GROUP BY CustomerNo, 
           DATEPART(mm,InvoiceDate), 
           TYPE
     ) p 
PIVOT (SUM(Cost)  FOR [Type] IN ([N],[R],[T],[U],[D]))AS pvt 
    ORDER BY Month

1 个答案:

答案 0 :(得分:0)

这是一种相当快速的方式(在编程时间内)来实现你想要的东西:

;
WITH details  -- Wrap your original query in a CTE so as to encapsulate all your calculations
AS (
SELECT Month, 
    [N] AS Expected, 
    [R] AS Requested, 
    [T] AS Tires, 
    [U] AS Unexpected, 
    [D] AS Damage,
    ISNULL([N],0) + ISNULL([R],0) + ISNULL([T],0) + ISNULL([U],0) + ISNULL([D], 0) as Total
FROM (
  SELECT CustomerNo, 
         DATEPART(mm,InvoiceDate) AS Month, 
         [Type], 
         SUM(Total) AS Cost 
   FROM  tbl_PM_History 
   WHERE (InvoiceDate >= @Start) 
     AND (InvoiceDate <= @End) 
     AND (CustomerNo = @Cust) 
   GROUP BY CustomerNo, 
         DATEPART(mm,InvoiceDate), 
         TYPE
   ) p 
PIVOT (SUM(Cost)  FOR [Type] IN ([N],[R],[T],[U],[D])) AS pvt 
)
,  summary  // Use another CTE to add a total line, using UNION ALL
AS (
  SELECT Month
     ,   Expected,
     ,   Requested
     ,   Tires
     ,   Unexpected
     ,   Damage
     ,   Total
     ,   0 as RecordCode
 FROM    details
 UNION ALL
 SELECT  Null
     ,   SUM(Expected)
     ,   SUM(Requested)
     ,   SUM(Tires)
     ,   SUM(Unexpected)
     ,   SUM(Damage)
     ,   SUM(Total)
     ,   1
 FROM    details
 )
 SELECT  Month  -- Do your actual sorting.
     ,   Expected,
     ,   Requested
     ,   Tires
     ,   Unexpected
     ,   Damage
     ,   Total
FROM  summary
ORDER by RecordCode, Month