T-SQL - 如何将多行交换为一列

时间:2011-10-12 09:57:27

标签: sql tsql plsql

我有像这样的结果集结构

code    Value
1       A0001
1       A0002
2       B0001
2       B0002
2       B0003
3       C0001
4       D0001
4       D0002
..       ...

我想谈谈这个:

ID     Response
1       A0001, A0002
2       B0001, B0002, B0003
3       C0001
4       D0001, D0002
...       ...

使用SQL。有没有办法使用T-SQL执行此操作? (和PL / SQL)

非常感谢!


感谢t-clausen.dk

有效。 但我想使用一个查询(可能与子查询)。 我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

对于T-SQL,我会使用这样的东西:

;with sample_data AS
(
SELECT 1 as code,'A0001' as [value]
UNION ALL SELECT 1,'A0002'
UNION ALL SELECT 2,'B0001'
UNION ALL SELECT 2,'B0002'
UNION ALL SELECT 2,'B0003'
UNION ALL SELECT 3,'C0001'
UNION ALL SELECT 4,'D0001'
UNION ALL SELECT 4,'D0002'
)
SELECT
code
,STUFF((
    SELECT
      ', ' + sd2.[value]
    FROM sample_data sd2
    WHERE sd1.code = sd2.code
    FOR XML PATH('')
    ), 1, 1, ''
  )
FROM sample_data sd1
GROUP BY sd1.code

对于PL / SQL的AS不知道我害怕!

答案 1 :(得分:1)

这是为mssql编写的,并改为我希望是oracle语法。如果有效,请告诉我。

declare @t table(code int, value varchar(20))
insert @t values(1,'A0001') 
insert @t values(1,'A0002') 
insert @t values(2,'B0001')
insert @t values(2,'B0002') 
insert @t values(2,'B0003') 
insert @t values(3,'C0001') 
insert @t values(4,'D0001') 
insert @t values(4,'D0002') 

;with a as
(select code, 
row_number() over (partition by code order by value) rna, 
row_number() over (partition by code order by value desc) rnd, 
value 
from @t
), b as
(
select code, rnd, value, rna, cast(value as varchar(2000)) outvalue from a where rna = 1
union all
select a.code, a.rnd, a.value, a.rna, cast(b.outvalue || ',' || a.value as varchar(2000))
from a 
join b on a.rna - 1 = b.rna and a.code = b.code
)
select code, outvalue from b
where rnd = 1
order by 1
--option (maxrecursion 0) -- not sure this is pl/sql

答案 2 :(得分:0)

对于PL / SQL

SELECT DISTINCT CODE as ID, LISTAGG(VALUE, ',')  
       WITHIN GROUP(ORDER BY code) OVER(PARTITION BY CODE) AS Response
       FROM TableName ORDER BY CODE;