将行转置为单列

时间:2011-09-16 14:29:05

标签: sql sql-server

我正在使用SQLServer。我有一个查询,它给出了以下结果。

1 Apple
1 Banana
1 Orange

在SQL中是否存在将其转移到以下内容:

1 Apple Banana Orange

4 个答案:

答案 0 :(得分:5)

SELECT DISTINCT id, names = STUFF((SELECT ' ' + name
    FROM dbo.[table] WHERE id = t.id
    FOR XML PATH('')), 1, 1, '')
FROM dbo.[table] AS t
-- WHERE id = 1
;

答案 1 :(得分:2)

您没有指定哪个DBMS,所以我假设Oracle:

SELECT id, LISTAGG(name, ' ') WITHIN GROUP (ORDER BY id)
FROM   your_table
GROUP BY id;

SELECT id, wm_concat(name)
FROM   your_table
GROUP BY id;

答案 2 :(得分:2)

在SQL SERVER 2005中,您可以使用xml,类似这样的

SELECT
  [Name] + ' ' as [text()] 
FROM fruits 
ORDER BY [Name] 
FOR XML path('')

for example

WITH fruits ([No],[Name]) AS (
SELECT
    1 , 'Apple1'  
UNION SELECT
    1, 'Banana1'
UNION SELECT
    1, 'Orange1'

UNION SELECT
    2, 'Apple2'
UNION SELECT
    2, 'Banana2'
UNION SELECT
    2, 'Orange2')

SELECT 
    [Name] + ' ' as [text()] 
FROM (SELECT [No], [Name] FROM fruits ) as fr 
ORDER BY [Name] 
FOR XML PATH('')

GO

或者如果您喜欢更一般的例子:

 WITH fruits ([No],[Name]) AS (
SELECT
    1 , 'Apple1'  
UNION SELECT
    1, 'Banana1'
UNION SELECT
    1, 'Orange1'

UNION SELECT
    2, 'Apple2'
UNION SELECT
    2, 'Banana2'
UNION SELECT
    2, 'Orange2')

SELECT 
    ft.[No], 
    (select [Name] + ' ' as [text()] from (SELECT [No], [Name] FROM fruits ) as fr where fr.[No] = ft.[No] ORDER BY [Name] for xml path('') ) as [Names]
 FROM 
    fruits ft
 GROUP BY [No]

注意:请记住删除[Names]

中的最后一个空格

答案 3 :(得分:1)

MSSQL表示 fruit 的已知值

with T(id, fruity) as (
   select 1, 'Apple'  union
   select 1, 'Banana' union
   select 1, 'Orange' union
   select 2, 'Apple'  union
   select 2, 'Banana' union
   select 3, 'Orange' 
)
SELECT * FROM T
PIVOT (
    MAX(fruity) 
    FOR fruity in ([Apple],[Banana],[Orange])
) pv

>>

id  Apple   Banana  Orange
1   Apple   Banana  Orange
2   Apple   Banana  NULL
3   NULL    NULL    Orange