在数据透视查询中创建总计

时间:2013-12-24 07:00:25

标签: sql-server sql-server-2008-r2

以下是我的查询

SELECT UserName ,
       TotCount ,
       EntryDate
FROM   @CandidateCount AS cc

以上查询的输出为

UserName   TotCount   EntryDate
--------------------------------
neelam       2        17/12/2013
neelam       1        18/12/2013
neelam       6        19/12/2013
snehal       7        17/12/2013
snehal       0        18/12/2013
snehal       2        19/12/2013

我已更新以上查询

 SELECT *
 FROM   ( SELECT    EntryDate ,
                UserName ,
                TotCount
          FROM      @CandidateCount AS tbl
        ) AS SourceTable PIVOT
    ( SUM(TotCount) FOR UserName IN ( [neelam], [snehal] ) )AS PivotTable
 ORDER BY EntryDate DESC

以上查询的输出为

  EntryDate    neelam    snehal
  19/12/2013     6        2
  18/12/2013     1        0
  17/12/2013     2        7

现在我想像这样做总日期

 EntryDate    neelam    snehal    Total
 19/12/2013     6         2        8
 18/12/2013     1         0        1
 17/12/2013     2         7        9

我该怎么做?感谢。

1 个答案:

答案 0 :(得分:0)

我已将您的数据放在名为Source的CTE中,以举例说明。使用另一个CTE,您可以轻松地将您的总数放在一边。您可以稍后在两个EntryDates上加入这些总计:

WITH Source AS (
    SELECT 'neelam' AS UserName, 2 AS TotCount, '17/12/2013' AS EntryDate UNION
    SELECT 'neelam' AS UserName, 1 AS TotCount, '18/12/2013' AS EntryDate UNION
    SELECT 'neelam' AS UserName, 6 AS TotCount, '19/12/2013' AS EntryDate UNION
    SELECT 'snehal' AS UserName, 7 AS TotCount, '17/12/2013' AS EntryDate UNION
    SELECT 'snehal' AS UserName, 0 AS TotCount, '18/12/2013' AS EntryDate UNION
    SELECT 'snehal' AS UserName, 2 AS TotCount, '19/12/2013' AS EntryDate
)

, Totals AS (
    SELECT      EntryDate
                    , SUM(TotCount) AS Total
    FROM        Source
    GROUP BY    EntryDate
)

SELECT PivotTable.*
       , Totals.Total
 FROM   ( SELECT    EntryDate ,
                UserName ,
                TotCount
          FROM      Source AS tbl
        ) AS SourceTable PIVOT
    ( SUM(TotCount) FOR UserName IN ( [neelam], [snehal] ) )AS PivotTable
 JOIN Totals ON PivotTable.EntryDate = Totals.EntryDate
 ORDER BY PivotTable.EntryDate DESC

在您的确切情况下:

WITH Totals AS (
    SELECT      EntryDate
                    , SUM(TotCount) AS Total
    FROM        @CandidateCount
    GROUP BY    EntryDate
)

SELECT PivotTable.*
       , Totals.Total
 FROM   ( SELECT    EntryDate ,
                UserName ,
                TotCount
          FROM @CandidateCount AS tbl
        ) AS SourceTable PIVOT
    ( SUM(TotCount) FOR UserName IN ( [neelam], [snehal] ) )AS PivotTable
 JOIN Totals ON PivotTable.EntryDate = Totals.EntryDate
 ORDER BY PivotTable.EntryDate DESC