2012-09-22 28 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