日期:2014-05-17  浏览次数:20484 次

如何把分类加和结果填入某一列中
本帖最后由 cndenis 于 2013-01-07 23:49:21 编辑
大家好,我是SQL初学者,现在一数据表,如下:

组名 权重 组内加和
1    3    NULL
1    4    NULL
1    5    NULL
2    1    NULL
2    2    NULL
2    3    NULL

目前第三列[组内加和]是空的,我想把它设为组名相同的权重的和,例如头三列为(3+4+5)=12,后三列为(1+2+3)=6

应该如何用SQL命令实现?
sql

------解决方案--------------------
Create TABLE #TB (组名 int,权重 int,组内加和 int)
INSERT INTO #TB select '1', '3', null
      union all select '1', '4', null
      union all select '1', '5', null
      union all select '2', '1', null
      union all select '2', '2', null
      union all select '2', '3', null

;with cet as
(select 组名,SUM(权重)权重 from #TB group by 组名)
update #TB set 组内加和 = b.权重 from #TB a, cet b where a.组名 = b.组名 
select * from #TB

/*组名          权重          组内加和
----------- ----------- -----------
1           3           12
1           4           12
1           5           12
2           1           6
2           2           6
2           3           6

(6 行受影响)

*/

------解决方案--------------------
----------------------------
-- Author  :DBA_Huangzj(发粪涂墙)
-- Date    :2013-01-07 23:53:02
-- Version:
--      Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (Intel X86) 
-- Jun 17 2011 00:57:23 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([组名] int,[权重] int,[组内加和] sql_variant)
insert [huang]
select 1,3,null union all
select 1,4,null union all
select 1,5,null union all