简体   繁体   中英

How to add rows that is grouped by a new group in mysql?

Update: This is a different question to the previous one, when I use ROLLUP in this question, it will add a total row, but I only want a group C to combine group A and B, thus group C shows the subtotal of color X, Y and Z. No total row needed.

I have data like this

Group Color Money
A     X     100
A     X     300
A     Y     200
B     X     200
B     Y     300
B     Y     100
B     Z     110

I want to make a new Group C that contains A&B

Is there anyway to query out data in mysql like this?

Group Color SumMoney AvgMoney DataCount
A     X     400      200      2
A     Y     200      200      1
B     X     200      200      1
B     Y     400      200      2    
B     Z     110      110      1
C     X     600      200      3
C     Y     600      200      3
C     Z     110      110      1

I think UNION may solve the problem but it may also be slow and the syntax would be long(harder to maintain(not in this case)). Any suggestions? Thanks!

Use UNION ALL in MySQL:

SELECT
    g.`group`,
    g.color,
    sum(g.money) AS SumMoney,
    CAST(AVG(g.money) AS SIGNED) AS AvgMoney,
    COUNT(g.`group`) AS DataCount
FROM
    groups g
GROUP BY
    g.`group`,
    g.color

UNION ALL

SELECT
    'C',
    g.color,
    sum(g.money) AS SumMoney,
    CAST(AVG(g.money) AS SIGNED) AS AvgMoney,
    COUNT(g.`group`) AS DataCount
FROM
    groups g
GROUP BY
    g.color

Output is:

group | color | SumMoney | AvgMoney | DataCount
-----------------------------------------------
A     | X     |      400 |      200 |        2
A     | Y     |      200 |      200 |        1
B     | X     |      200 |      200 |        1
B     | Y     |      400 |      200 |        2
B     | Z     |      110 |      110 |        1
C     | X     |      600 |      200 |        3
C     | Y     |      600 |      200 |        3
C     | Z     |      110 |      110 |        1
select group,color,sum(money) as SumMoney ,avg(money) as AvgMoney,
       count(*) as DataCount from table_name group by group,color 

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