SQL在一列中选择多行

时间:2022-02-11 12:28:17

I have table TestTable

我有表TestTable

ID Name
-------
1  A
1  B
1  C 
2  D 
2  E
3  F

I want to write a query in SQL Server 2008 which will return

我想在SQL Server 2008中编写一个将返回的查询

ID Name
----------    
1   A,B,C
2   D,E
3   F

Please someone help me to write this query.

请有人帮我写这个查询。

3 个解决方案

#1


15  

AFAIK, there is no native way to do so. However, you can use the FOR XML to do this like so:

AFAIK,没有本地方式这样做。但是,您可以使用FOR XML来执行此操作:

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 Demo

This will give you:

这会给你:

| ID |   NAMES |
----------------
|  1 | A, B, C |
|  2 |    D, E |
|  3 |       F |

#2


0  

SQL server 2008 supports this by using Pivot or Unpivot @ http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

SQL Server 2008通过使用Pivot或Unpivot来支持这一点@ http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

#3


0  

try this ::

尝试这个 ::

SELECT  a.ID, 
        SUBSTRING(d.Name,1, LEN(d.Name) - 1) Name
FROM
        (
            SELECT DISTINCT ID
            FROM testTable
        ) a
        CROSS APPLY
        (
            SELECT [Name] + ', ' 
            FROM testTable AS B 
            WHERE A.ID = B.ID 
            FOR XML PATH('')
        ) D (Name)  

#1


15  

AFAIK, there is no native way to do so. However, you can use the FOR XML to do this like so:

AFAIK,没有本地方式这样做。但是,您可以使用FOR XML来执行此操作:

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 Demo

This will give you:

这会给你:

| ID |   NAMES |
----------------
|  1 | A, B, C |
|  2 |    D, E |
|  3 |       F |

#2


0  

SQL server 2008 supports this by using Pivot or Unpivot @ http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

SQL Server 2008通过使用Pivot或Unpivot来支持这一点@ http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

#3


0  

try this ::

尝试这个 ::

SELECT  a.ID, 
        SUBSTRING(d.Name,1, LEN(d.Name) - 1) Name
FROM
        (
            SELECT DISTINCT ID
            FROM testTable
        ) a
        CROSS APPLY
        (
            SELECT [Name] + ', ' 
            FROM testTable AS B 
            WHERE A.ID = B.ID 
            FOR XML PATH('')
        ) D (Name)