0

我有这张桌子:

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 并按名称分组但合并地址(因为每个名称的地址总是相同的)

4

5 回答 5

1

您需要按姓名和地址分组:

SELECT name, address, sum(count1), sum(count2)
FROM table
GROUP BY name, address
于 2012-10-31T21:44:41.277 回答
1

所以你想按姓名地址分组:

select name, sum(count1)as count1, sum(count2)as count2, address
from dbo.table
group by name, address;

基本上是GROUP BY 合并记录。

于 2012-10-31T21:45:11.540 回答
1

使用以下查询。您如何包含地址实际上取决于您使用的数据库。

select name, sum(count1) count1,sum(count2) count2 ,address
from table1
group by name, address

SQLFiddle 玩

于 2012-10-31T21:50:30.407 回答
0

这是 SQL 聚合 101(我还在学习,顺便说一句):

select name, sum(count1), sum(count2), address
from mytable
group by name, address;
于 2012-10-31T21:44:10.637 回答
0

如果您不喜欢按解决方案进行双重分组,您也可以使用 select inside from:

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
于 2012-10-31T22:09:33.400 回答