2012-09-12 46 views
2

如果我除了一个外地在SQL数据库几行(访问前端)近确切的数据(我知道正常化,但我很高兴地说,这不是我做的!),有一个简单的方法来选择一排与普通数据并显示其他字段中的所有值加在一起?我可以编写一个函数以编程方式执行,但我认为有一个更简单的方法?选择行,除了

animal brown dog 

animal brown cat 

animal brown horse 

animal brown dog, cat, horse 
+1

您正在查找字符串聚合连接操作。它因数据库而异。你应该在你的问题中提到数据库。得到答案的最快方法是通过google搜索类似“通过SQL字符串连接组”。 –

+0

SQL Server中,但Google搜索你所提到的,得到它,谢谢 – DarkW1nter

回答

3

您可以使用STUFF()得到这个:

select distinct col1, col2, 
    Stuff((SELECT N', ' + col3 
     FROM yourtable t2 
     where t1.col1 = t2.col1 
     FOR XML PATH(''),TYPE) 
     .value('text()[1]','nvarchar(max)'),1,2,N'') 
from yourtable t1 

请参阅SQL Fiddle with Demo

1

这里是你需要使用的技术的例子:

select 'test' as Test, 1 as Item 
into #test 
union select 'test2', 2 
union select 'test', 3 
union select NUll, 4 
union select 'test', 5 

select t2.test, STUFF((SELECT ', ' + cast(t1.Item as varchar (10)) 
     FROM #test t1 where t2.test = t1.test 
     FOR XML PATH('')), 1, 1, '') 
    from #test t2 
    group by t2.test