Reputation: 125
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!
Upvotes: 1
Views: 274
Reputation: 881
select group,color,sum(money) as SumMoney ,avg(money) as AvgMoney,
count(*) as DataCount from table_name group by group,color
Upvotes: 0
Reputation: 5316
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
Upvotes: 1