基于重复的MySQL小计

时间:2013-10-29 12:14:31

标签: mysql

所以我在MySQL中有以下表格:

Table1:
Col1  Team
100   A
100   B
100   C
200   D
200   A
200   C
300   A

Table2:
Team  Col2
A     1
B     2
C     3
D     4

我想要做的是获得Table2.Col2的总和,并按Team分组,其中Table1.Col1中有重复(多次出现)。所需的输出应为:

Col1  Col2
100   3     ( 1 + 2 + 3 )
200   8     ( 1 + 3 + 4 )

不应输出Col1的值300,因为表1中只有一个实例。

2 个答案:

答案 0 :(得分:2)

select t1.col1, sum(t2.col2)
from table1 t1
left join table2 t2 on t1.team = t2.team
group by t1.col1
having count(t1.team) > 1

答案 1 :(得分:0)

如果我理解正确,那么答案就是

select table1.Col1, Sum(table2.Col2) from table1 
left join table2 on table1.Team = table2.Team group by Col1 
having count(table1.Col1) > 1