sql server 表中如何把ID相同的行再把的同一个字段值相加
如题
表A
ID name num
1 电脑 2000
2 手机 3000
1 电脑 223
2 手机 423
... ... ...
查询后
ID name num
1 电脑 2223
2 手机 3423 SQL?Server 汇总
[解决办法]
select ID,Name,sum(num) as num
from tb
group by ID,Name
[解决办法]
select ID,Name,sum(num) as num
from 表A
group by ID,Name
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-08-14 10:19:31
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
--Jun 10 2013 20:09:10
--Copyright (c) Microsoft Corporation
--Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([ID] int,[name] varchar(4),[num] int)
insert [A]
select 1,'电脑',2000 union all
select 2,'手机',3000 union all
select 1,'电脑',223 union all
select 2,'手机',423
--------------开始查询--------------------------
select [id],[name],SUM([num])[num]
from [A]
GROUP BY [id],[name]
----------------结果----------------------------
/*
id name num
----------- ---- -----------
1 电脑 2223
2 手机 3423
*/
SELECT id, name=MIN(name), num=SUM(num)
FROM 表A
GROUP BY id
ORDER BY id
select name,SUM(num) as num from a group by id,name
select ID,Name,sum(num) as num
from [表名]
group by ID,Name