显示每个组的新行中的分组列的总和

时间:2014-09-19 15:11:10

标签: sql sql-server group-by

我想在sql结果集中显示每个组之后的数据总和。

我有两个表组1

-------------------------------------
Group       Name        Sale
-------------------------------------
G1          ABC1        10
.....................................
G1          ABC2        20
.....................................
G1          ABC3        40

和第2组

-------------------------------------
Group       Name        Sale
.....................................
G2          XYZ1        34
.....................................
G2          XYZ2        14
.....................................
G2          XYZ3        44

我想显示如下数据:

-------------------------------------
Group       Name        Sale
-------------------------------------
G1          ABC1        10
.....................................
G2          XYZ1        34
.....................................
TOTAL       TOTAL       44                -- Calculated Row
.....................................
G1          ABC2        20
.....................................
G2          XYZ2        14
.....................................
TOTAL       TOTAL       34                -- Calculated Row
.....................................
G1          ABC3        40
.....................................
G2          XYZ3        44
.....................................
TOTAL       TOTAL       84                -- Calculated Row
.....................................

这可能吗?

1 个答案:

答案 0 :(得分:1)

我在这里做了一些假设。即名称"名称"总是4个字符,如果它结束于" 1"然后它与另一个表中的名称相关,该名称也以" 1"结尾。您可以在派生的UnionTotal表中最后一个联合SELECT语句的LEFT OUTER JOIN中看到这一点。

SELECT
    *
FROM
    (
        SELECT
            Substring(name, 4, 1) as sortOrder,
            Group,
            Name,
            Sale
        FROM Group1
        UNION ALL
        SELECT
            Substring(Name, 4, 1) as sortOrder,
            Group,
            Name,
            Sale
        FROM Group2
        UNION ALL
        SELECT
            Substring(G1.Name, 4, 1) as sortOrder,
            "Total" as Group,
            "Total" as Name,
            G1.Sale + G2.Sale as Sale
        FROM
            Group1 as G1
            LEFT OUTER JOIN Group2 as G2 ON
                Substring(G1.Name, 4, 1) = Substring(G2.Name, 4, 1)

    ) as unionTotal
ORDER BY sortOrder, Group;