?
http://www.iteye.com/topic/774205
?
一道有趣的sql题
field1? field2?
A???????? 1?
A???????? 2?
A???????? 3?
用一条sql语句查询成:?
field1?? all?
A??????? 1,2,3,?
?
准备数据
?
CREATE TABLE [dbo].[test](
[c1] [varchar](50) NULL,
[c2] [int] NULL
) ON [PRIMARY]
insert into dbo.test(c1,c2) values('A',1)
insert into dbo.test(c1,c2) values('A',2)
insert into dbo.test(c1,c2) values('A',3)
insert into dbo.test(c1,c2) values('B',1)
insert into dbo.test(c1,c2) values('B',2)
MYSQL?的方法(未验证)
select c1,group_concat(c2) as all from ?dbo.test ?group by c1
?
SQL SERVER 的方法 (验证)
select c1,c2=stuff((select ','+cast(c2 as varchar(100)) from dbo.test?
? ? ? where c1=a.c1 ?for XML path('')),1,1,'')
from dbo.test a GROUP BY c1
?
结果:
A 1,2,3
B 1,2
?
功能:拼C1为A的字符串
语句:select ','+cast(c2 as varchar(100)) from dbo.test WHERE c1 = 'A' ? ?for XML path('')
输出: ,1,2,3
?
功能:去掉首字符,
语句:stuff(string,1,1,'')
输出:1,2,3
?
for XML path 真是个好东东呢,具体使用方法见http://blog.csdn.net/pengxuan/article/details/6609043