表A:物料大类,物料小类,数量,接受库管员
想得到如下结果:
select 物料大类,物料小类,sum(数量),(这里同时想得到:几个不同的库管员,因为同一个库管员可能接受多个) from 表A
谢谢!
------解决方案--------------------
- SQL code
if object_id('test1') is not null drop table test1;gocreate table test1( [物料大类] nvarchar(20) not null, [物料小类] nvarchar(20) not null, [数量] int not null, [接受管理员] nvarchar(10));insert into test1select '粮食', '大米', 200, '管理员1' union allselect '粮食', '大米', 36, '管理员2' union allselect '粮食', '大米', 45, '管理员3' union allselect '粮食', '玉米', 67, '管理员2' union allselect '粮食', '玉米', 900, '管理员5' union allselect '粮食', '玉米', 23, '管理员7' union allselect '粮食', '玉米', 65, '管理员8' union allselect '粮食', '小麦', 345, '管理员5' union allselect '油料', '油菜', 45, '管理员3' union allselect '油料', '油菜', 67, '管理员3' union allselect '油料', '油菜', 88, '管理员4'goselect [物料大类], [物料小类], sum([数量]) as [总数量], count( distinct [接受管理员]) as [管理员数]from test1group by [物料大类], [物料小类]/*查询结果:物料大类 物料小类 总数量 管理员数-------------------- -------------------- ----------- -----------粮食 大米 281 3粮食 小麦 345 1粮食 玉米 1055 4油料 油菜 200 2*/
------解决方案--------------------
- SQL code
if object_id('test1') is not null drop table test1;gocreate table test1( [物料大类] nvarchar(20) not null, [物料小类] nvarchar(20) not null, [数量] int not null, [接受管理员] nvarchar(10));insert into test1select '粮食', '大米', 200, '管理员1' union allselect '粮食', '大米', 36, '管理员2' union allselect '粮食', '大米', 45, '管理员3' union allselect '粮食', '玉米', 67, '管理员2' union allselect '粮食', '玉米', 900, '管理员5' union allselect '粮食', '玉米', 23, '管理员7' union allselect '粮食', '玉米', 65, '管理员8' union allselect '粮食', '小麦', 345, '管理员5' union allselect '油料', '油菜', 45, '管理员3' union allselect '油料', '油菜', 67, '管理员3' union allselect '油料', '油菜', 88, '管理员4'goselect [物料大类], [物料小类], sum([数量]) as [总数量], [接受管理员]=STUFF((SELECT ','+t2.[接受管理员] FROM test1 t2 WHERE t1.[物料大类]=t2.[物料大类] AND t1.[物料小类]=t2.[物料小类] FOR XML PATH('')),1,1,'')from test1 t1group by t1.[物料大类], t1.[物料小类]/*物料大类 物料小类 总数量 接受管理员-------------------- -------------------- ----------- ----------------------------------------------------------------------------------------------------------------粮食 大米 281 管理员1,管理员2,管理员3粮食 小麦 345 管理员5油料 油菜 200 管理员3,管理员3,管理员4粮食 玉米 1055 管理员2,管理员5,管理员7,管理员8(4 行受影响)*/