mysql sum union结果

时间:2013-03-04 09:48:18

标签: sql sum union

见下面的样本。如果id,A,B,D与其他记录相同,那么union和sum列“C”

my data:
id A  B  C  D
---------------------------
1  1  2  3  4
2  aa bb 10 dd
3  1  2  3  4
4  1  2  3  4
2  aa bb 30 dd

how to do after like below result:
id A  B  C  D
---------------------------
1  1  2  3  4
2  aa bb 40 dd    <----if id,A,B,D are same with other records,then union and sum column "C"
3  1  2  3  4
4  1  2  3  4

I tried to union all records,but fail and show"
id A  B  C  D
---------------------------
2  aa bb 49 dd 

1 个答案:

答案 0 :(得分:0)

只需使用GROUP BY ID, A, B, D SUM(C),就像这样:

SELECT id, A,  B,  SUM(C) AS C,  D
FROM Tablename
GROUP BY ID, A, B, D;

SQL Fiddle Demo