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

请问查询结果显示有关问题

2012-05-24 
请教查询结果显示问题查询name一列,select name from users where ……结果显示为:name张三李四王五……现在想

请教查询结果显示问题
查询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 @SQL=@SQL+' FROM #t GROUP BY item_id'exec (@SQL)drop table #tdrop table #tt --删除测试环境Drop Table 表go/*1    李四    王五    张三2    老七    赵六    NULL*/ 

热点排行