更新:这是与前一个问题不同的问题,当我在这个问题中使用ROLLUP时,它会添加一个总行,但我只想要一个C组来组合A组和B组,因此C组显示了小计颜色X,Y和Z.不需要总排。
我有这样的数据
Group Color Money
A X 100
A X 300
A Y 200
B X 200
B Y 300
B Y 100
B Z 110
我想创建一个包含A& B
的新C组有没有像这样在mysql中查询数据?
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
我认为UNION可以解决这个问题,但它也可能很慢而且语法很长(难以维护(不是在这种情况下))。有什么建议?谢谢!
答案 0 :(得分:1)
在MySQL中使用UNION ALL
:
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
输出是:
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
答案 1 :(得分:0)
select group,color,sum(money) as SumMoney ,avg(money) as AvgMoney,
count(*) as DataCount from table_name group by group,color