日期:2014-05-18 浏览次数:20897 次
if object_id('test1') is not null
drop table test1;
go
create table test1
(
[物料大类] nvarchar(20) not null,
[物料小类] nvarchar(20) not null,
[数量] int not null,
[接受管理员] nvarchar(10)
);
insert into test1
select '粮食', '大米', 200, '管理员1' union all
select '粮食', '大米', 36, '管理员2' union all
select '粮食', '大米', 45, '管理员3' union all
select '粮食', '玉米', 67, '管理员2' union all
select '粮食', '玉米', 900, '管理员5' union all
select '粮食', '玉米', 23, '管理员7' union all
select '粮食', '玉米', 65, '管理员8' union all
select '粮食', '小麦', 345, '管理员5' union all
select '油料', '油菜', 45, '管理员3' union all
select '油料', '油菜', 67, '管理员3' union all
select '油料', '油菜', 88, '管理员4'
go
select [物料大类], [物料小类], sum([数量]) as [总数量], count( distinct [接受管理员]) as [管理员数]
from test1
group by [物料大类], [物料小类]
/*查询结果:
物料大类 物料小类 总数量 管理员数
-------------------- -------------------- ----------- -----------
粮食 大米 281 3
粮食 小麦 345 1
粮食 玉米 1055 4
油料 油菜 200 2
*/
------解决方案--------------------
if object_id('test1') is not null
drop table test1;
go
create table test1
(
[物料大类] nvarchar(20) not null,
[物料小类] nvarchar(20) not null,
[数量] int not null,
[接受管理员] nvarchar(10)
);
insert into test1
select '粮食', '大米', 200, '管理员1' union all
select '粮食', '大米', 36, '管理员2' union all
select '粮食', '大米', 45, '管理员3' union all
select '粮食', '玉米', 67, '管理员2' union all
select '粮食', '玉米', 900, '管理员5' union all
select '粮食', '玉米', 23, '管理员7' union all
select '粮食', '玉米', 65, '管理员8' union all
select '粮食', '小麦', 345, '管理员5' union all
select '油料', '油菜', 45, '管理员3' union all
select '油料', '油菜', 67, '管理员3' union all
select '油料', '油菜', 88, '管理员4'
go
select [物料大类], [物料小类], sum([数量]) as [总数量],
[接受管理员]=STUFF((SELECT ','+t2.[接受管理员] FROM test1 t2
WHERE t1.[物料大类]=t2.[物料大类] AND t1.[物料小类]=t2.[物料小类] FOR XML PATH('')),1,1,'')
from test1 t1
group by t1.[物料大类], t1.[物料小类]
/*物料大类 物料小类 总数量 接受管理员
-------------------- -------------------- ----------- ----------------------------------------------------------------------------------------------------------------
粮食 大米 281 管理员1,管理员2,管理员3
粮食 小麦 345 管理员5
油料 油菜 200 管理员3,管理员3,管理员4
粮食 玉米 1055 管理员2,管理员5,管理员7,管理员8
(4 行受影响)*/