2011-10-12 29 views
1

我有一個結果的結構是這樣T-SQL - 如何多行交換到一列

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

的IT工作。 但我想使用一個查詢(可能與子查詢)。 我該怎麼做?

+0

您正在尋找模擬'爲SQL Server GROUP_CONCAT'你會使用'XML PATH'在PLSQL –

回答

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 

AS的PL/SQL不知道我怕!

+0

不知道,我也嘗試了這一點,你打我通過這部分查詢WHERE sd1.code = sd2.code – rahularyansharma

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 
+0

任何人都可以確認這個工作嗎?我有6年沒有訪問oracle。 –

+0

謝謝t-clausen.dk – sdev

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;