简体   繁体   中英

Show sum of grouped column in new row for each group

I want to show sum of data after each group in the sql result set.

I have two table Group 1

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

and Group 2

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

I want to show data like below :

-------------------------------------
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
.....................................

is this possible ?

I made some assumptions here. Namely that the "Name" is always 4 characters and if it ends in "1" then it is related to the Name from the other table that also ends in "1". You can see this in the the LEFT OUTER JOIN in the last unionized SELECT statement in the derived UnionTotal table.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM