SQL选择一列中的多行 [英] SQL select multiple rows in one column
本文介绍了SQL选择一列中的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有表 TestTable
ID Name
-------
1 A
1 B
1 C
2 D
2 E
3 F
我想在 SQL Server 2008 中编写一个将返回的查询
I want to write a query in SQL Server 2008 which will return
ID Name
----------
1 A,B,C
2 D,E
3 F
请有人帮我写这个查询.
Please someone help me to write this query.
推荐答案
AFAIK,没有本地方法可以这样做.但是,您可以使用 FOR XML代码>
这样做:
AFAIK, there is no native way to do so. However, you can use the FOR XML
to do this like so:
SELECT
t1.Id,
STUFF((
SELECT ', ' + t2.name
FROM Table1 t2
WHERE t2.ID = t1.ID
FOR XML PATH (''))
,1,2,'') AS Names
FROM Table1 t1
GROUP BY t1.Id;
SQL Fiddle 演示
这会给你:
SQL Fiddle Demo
This will give you:
| ID | NAMES |
----------------
| 1 | A, B, C |
| 2 | D, E |
| 3 | F |
这篇关于SQL选择一列中的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文