我有这张桌子:
name count1 count2 address
John 5 0 London
John 0 3 London
Phil 1 0 Paris
我想要
name count1 count2 address
John 5 3 London
Phil 1 0 Paris
所以我想总结count1和sum count2和group by name但合并地址(因为每个名字的地址总是相同的)
答案 0 :(得分:1)
您需要按姓名和地址分组:
SELECT name, address, sum(count1), sum(count2)
FROM table
GROUP BY name, address
答案 1 :(得分:1)
因此,您希望按名称分组和地址:
select name, sum(count1)as count1, sum(count2)as count2, address
from dbo.table
group by name, address;
基本上GROUP BY
合并记录。
答案 2 :(得分:1)
使用以下查询。如何包含地址实际上取决于您使用的数据库。
select name, sum(count1) count1,sum(count2) count2 ,address
from table1
group by name, address
答案 3 :(得分:0)
这是SQL聚合101(我还在学习,顺便说一下):
select name, sum(count1), sum(count2), address
from mytable
group by name, address;
答案 4 :(得分:0)
如果你不喜欢解决方案的双重组,你也可以使用select inside:
select distinct temp.name, temp.count1, temp.count2, t.address
from mytable t, (select t2.name, sum(t2.count1) as count1, sum(t2.count2) as count2
from mytable t2
group by t2.name) as temp
where t.name = temp.name