2014-02-20 13 views
1

我有一個名爲RUGS的表,其數據如下。如何編寫TSQl查詢以獲取Output中所示的數據。我不熟悉UNPIVOT如何在單個行上獲取數據

`CONO ARtype天收入PPD

140 MCD 5 1000 500

140 MRA 6 2000 600

140 MRA 7 3000 700

141 MCD 1 5000 100

141 MRA 2 6000 200

141 MRA 3 7000 300`

結果

140 MCD 5 1000 500 6 MRA 2000 600 MRA 7 3000 700

141 MCD 1 5000 100 2 MRA 6000 200 MRA 3 7000 300

+0

你如何決定列的順序?每個ID總是有3個記錄?如果或多或少呢? – EricZ

+0

是 - 非常符合3條記錄。 cono應該只出現一次3條記錄。 – stackuser

+1

你問了同樣的問題之前http://stackoverflow.com/questions/21890782/getting-data-on-a-single-row,請不要問相同的問題兩次 – EricZ

回答

3

鑑於每個cono將有3條記錄(如評論中所述),cterow_number可以與case語句一起使用。

如果有少於三條記錄,您會在結果中看到空白和零。任何超過三個將不會有所有記錄。

這裏是@RUGS爲表變量的例子:

declare @RUGS table (cono int, ARType char(3), [days] int, Revenue int, PPD int) 

insert into @RUGS VALUES 
(140,'MCD',5,1000,500) 
,(140,'MRA',6,2000,600) 
,(140,'MRA',7,3000,700) 
,(141,'MCD',1,5000,100) 
,(141,'MRA',2,6000,200) 
,(141,'MRA',3,7000,300); 

with cte as 
(
    select row_number() over(partition by cono order by (select 1)) as rn, * from @RUGS 
) 

select cono, 
    max(case when rn = 1 then ARType else '' end) as ARType1, 
    max(case when rn = 1 then days else '' end) as days1, 
    max(case when rn = 1 then Revenue else '' end) as Revenue1, 
    max(case when rn = 1 then PPD else '' end) as PPD1, 
    max(case when rn = 2 then ARType else '' end) as ARType2, 
    max(case when rn = 2 then days else '' end) as days2, 
    max(case when rn = 2 then Revenue else '' end) as Revenue2, 
    max(case when rn = 2 then PPD else '' end) as PPD2, 
    max(case when rn = 3 then ARType else '' end) as ARType3, 
    max(case when rn = 3 then days else '' end) as days3, 
    max(case when rn = 3 then Revenue else '' end) as Revenue3, 
    max(case when rn = 3 then PPD else '' end) as PPD3  
from cte group by cono 
+0

非常感謝! – stackuser

相關問題