2012-09-22 26 views
2

我正在查找部分透視表而不使用PIVOT運算符(舊的ms-sql服務器)的查詢。 表:
無樞軸運算符的部分數據透視表

id-------item---------rank1---------rank2 
231------it1--------- 1 ----------- 1 
231------it2-------- 1 ----------- 2 
231------it3--------- 1 ----------- 3 
154------it4--------- 3 ----------- 4 
154------it2--------- 1 ----------- 2 
155------it2--------- 1 ----------- 2 
156------it3 -------- 2 ----------- 2 
156------it1 -------- 1 ----------- 1 

預期的結果:

id---------item1----item2----item3---item*... 
231 -------it1------it2---------it3 
154--------it2------it4 
155--------it2 
156--------it1------it3 

爲了通過秩1和秩2

我搜索的谷歌,但我找到了解決方案太複雜,無法適用。

+0

什麼版本的SQL Server? – Taryn

回答

1

在SQL Server中,可以使用row_number爲每個id組分配一個行號。然後你可以使用max(case(...招支點:

select id 
,  max(case when rn = 1 then item end) as item1 
,  max(case when rn = 2 then item end) as item2 
,  max(case when rn = 3 then item end) as item3 
from (
     select row_number() over (partition by id 
        order by rank1, rank2) as rn 
     ,  * 
     from YourTable 
     ) as SubQueryAlias 
group by 
     id 

有N個項目,而不使用動態SQL沒有通用的解決方案。

+0

我會盡力,謝謝你的快速回答..不知道我們可以結合最大和案件..
在這種特殊情況下(當然我很好理解)..我需要添加一條線
最大(案件時= 4,然後項目結束)作爲item4 – user1690564