我有一个连接表,我想从中总结属性数量,也可以按名称进行分组。
joined_tb
name attr amount
billy 'attr1' 2
billy 'attr2' 4
billy 'attr1' 7
billy 'attr3' 8
jean 'attr2' 6
jean 'attr1' 1
jean 'attr2' 11
此表是使用id
t1 t2
id name id attr amount
1 billy 1 'attr1' 2
2 jean 1 'attr2' 4
1 'attr1' 7
1 'attr3' 8
2 'attr2' 6
2 'attr1' 1
2 'attr2' 11
我想最终得到这张表:
result_tb
name attr amount
billy 'attr1' 9
billy 'attr2' 4
billy 'attr3' 8
jean 'attr1' 1
jean 'attr2' 17
我可以按attr
求和,但忽略name
。如何从result_tb
和t1
获取t2
?
答案 0 :(得分:3)
试试这个:
select t1.name, t2.attr, sum(t2.amount) from t1
join t2 on t1.id = t2.id
group by t1.name, t2.attr
答案 1 :(得分:1)
尝试下面的内容:
SELECT t1.name, t2.attr, sum(t2.amount) as totalamount
FROM table1 as t1 LEFT JOIN table2 as t2 on t1.id = t2.id
group by t1.name, t2.attr