首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

汇总语句(SQL2008)

2012-05-02 
求一个汇总语句(SQL2008)设有下表:idUserIDValue1100AA2100BB3101CC4100DD5101EE能否汇总出:UserIDtheGrou

求一个汇总语句(SQL2008)
设有下表:
id UserID Value
1 100 AA
2 100 BB
3 101 CC
4 100 DD
5 101 EE

能否汇总出:

UserID theGroup
100 AA,BB,DD
101 CC,EE 

谢谢!

[解决办法]

SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([id] int,[UserID] int,[Value] varchar(2))insert [test]select 1,100,'AA' union allselect 2,100,'BB' union allselect 3,101,'CC' union allselect 4,100,'DD' union allselect 5,101,'EE'SELECT *FROM (SELECT DISTINCT [UserID] FROM [test])AOUTER APPLY(    SELECT [values]= STUFF(REPLACE(REPLACE(            (   SELECT value FROM [test] N                WHERE [UserID] = A.[UserID]                FOR XML AUTO             ), '<N value="', ','), '"/>', ''), 1, 1, ''))N/*UserID    values100    AA,BB,DD101    CC,EE*/
[解决办法]
--> 测试数据:[test]
if object_id('[test]') is not null 
drop table [test]
create table [test](
[id] int,
[UserID] int,
[Value] varchar(2)
)
insert [test]
select 1,100,'AA' union all
select 2,100,'BB' union all
select 3,101,'CC' union all
select 4,100,'DD' union all
select 5,101,'EE'

Select Distinct userid,(select value+',' 
from test b where a.userid=b.userid
for xml path('')) theGroup
From test a

热点排行