如何在不对行数据进行分组的情况下将总计/小计添加到一组结果中?

时间:2010-05-21 18:32:16

标签: tsql grouping rollup

我正在为业务报告构建SQL查询。我需要在报告中包含小计(按文件编号分组)和总计。

我正在进入未知的SQL区域,所以这是第一次尝试。我所做的查询几乎正在运行。唯一的问题是条目被分组 - 我需要在报告中将它们分开。

以下是我的示例数据:

FileNumber        Date   Cost   Charge
         3   Dec 22/09      5       10
         3   Jan 13/10      6       15
        3B   Mar 28/10      1        3
        3B   Mar 28/10      5       10

当我运行此查询时

SELECT
    CASE
        WHEN (GROUPING(FileNumber) = 1) THEN NULL
        ELSE FileNumber
    END AS FileNumber,
    CASE
        WHEN (GROUPING(Date) = 1) THEN NULL
        ELSE Date
    END AS Date,
    SUM(Cost) AS Cost,
    SUM(Charge) AS Charge

    FROM SubtotalTesting
    GROUP BY FileNumber, Date WITH ROLLUP
    ORDER BY
        (CASE WHEN FileNumber IS NULL THEN 1 ELSE 0 END), -- Put NULLs after data
        FileNumber,
        (CASE WHEN Date IS NULL THEN 1 ELSE 0 END), -- Put NULLs after data
        Date

我得到以下内容:

FileNumber        Date  Cost  Charge
         3   Dec 22/09     5      10
         3   Jan 13/10     6      15
         3        NULL    11      25
        3B   Mar 28/10     6      13 <--
        3B        NULL     6      13
      NULL        NULL    17      38

想要的是:

FileNumber        Date  Cost  Charge
         3   Dec 22/09     5      10
         3   Jan 13/10     6      15
         3        NULL    11      25
        3B   Mar 28/10     1       3 <--
        3B   Mar 28/10     5      10 <--
        3B        NULL     6      13
      NULL        NULL    17      38

我可以清楚地看到为什么条目正在被分组,但我不知道如何在仍然返回小计和总计时将它们分开。

在进行这样的高级SQL查询时,我有点绿,所以如果我使用WITH ROLLUP采取错误的方法解决问题,请提出一些首选的选择 - 你不要我必须为我写整个查询,我只需要一些方向。谢谢!

1 个答案:

答案 0 :(得分:4)

WITH    SubtotalTesting (FileNumber, Date, Cost, Charge) AS
        (
        SELECT  '3', CAST('2009-22-12' AS DATETIME), 5, 10
        UNION ALL
        SELECT  '3', '2010-13-06', 6, 15
        UNION ALL
        SELECT  '3B', '2010-28-03', 1, 3
        UNION ALL
        SELECT  '3B', '2010-28-03', 5, 10
        ),
        q AS (
        SELECT  *,
                ROW_NUMBER() OVER (ORDER BY filenumber) AS rn
        FROM    SubTotalTesting
        )
SELECT  rn,
        CASE
                WHEN (GROUPING(FileNumber) = 1) THEN NULL
                ELSE FileNumber
        END AS FileNumber,
        CASE
                WHEN (GROUPING(Date) = 1) THEN NULL
                ELSE Date
        END AS Date,
        SUM(Cost) AS Cost,
        SUM(Charge) AS Charge
FROM    q
GROUP BY
        FileNumber, Date, rn WITH ROLLUP
HAVING  GROUPING(rn) <= GROUPING(Date)
ORDER BY
        (CASE WHEN FileNumber IS NULL THEN 1 ELSE 0 END),
        FileNumber,
        (CASE WHEN Date IS NULL THEN 1 ELSE 0 END),
        Date