查询name一列,select name from users where ……
结果显示为:
name
张三
李四
王五
……
现在想要改显示为:
name
张三,李四,王五,……
请教,如果实现?
------解决方案--------------------
- SQL code
if object_id('[TB]') is not null drop table [TB]gocreate table [TB] (name nvarchar(4))insert into [TB]select '张三' union allselect '李四' union allselect '王五'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都改成1insert into 表select '1','张三' unionselect '1','李四' unionselect '1','王五' unionselect '2','赵六' unionselect '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 aDECLARE @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) ASET @[email protected]+' FROM #t GROUP BY item_id'exec (@SQL)drop table #tdrop table #tt --删除测试环境Drop Table 表go/*1 李四 王五 张三2 老七 赵六 NULL*/