日期:2014-05-18  浏览次数:20446 次

请教查询结果显示问题
查询name一列,select name from users where ……
结果显示为:

name
张三
李四
王五
……

现在想要改显示为:
name
张三,李四,王五,……

请教,如果实现?

------解决方案--------------------
SQL code
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (name nvarchar(4))
insert into [TB]
select '张三' union all
select '李四' union all
select '王五'

select * from [TB]

select distinct  [name]=stuff((select ','+[name] from tb for xml path('')), 1, 1, '') 
from tb 

/*
张三,李四,王五*/

------解决方案--------------------
SQL code

给你份:

--建立测试环境
Create Table 表(Item_ID varchar(10),sel varchar(10))
--插入数据
--注意下面Item_ID这个字段,这是进行分组的,可以自己进行测试下,把2都改成1
insert into 表
select '1','张三' union
select '1','李四' union
select '1','王五' union
select '2','赵六' union
select '2','老七'
 
--测试语句

select id=identity(int),* into #tt from 表

select item_id,sel,orderId=cast((select count(*) from #tt where item_id=a.item_id and id<=a.id) as char(1))
into #t from #tt a

DECLARE @SQL VARCHAR(8000)
SET @SQL='SELECT item_id'
SELECT @SQL= @SQL+ ',MIN(CASE WHEN orderId = ''' + orderId + ''' THEN sel END) [数据' + orderId + ']' FROM (SELECT DISTINCT orderId FROM #T) A
SET @SQL=@SQL+' FROM #t GROUP BY item_id'
exec (@SQL)

drop table #t
drop table #tt
 
--删除测试环境
Drop Table 表
go
/*
1    李四    王五    张三
2    老七    赵六    NULL*/