2014-03-12 61 views
0

如何編寫SQL查詢以顯示如下所示的'期望輸出'中的輸出。該值必須在每種類型中以降序排列並並排顯示。如何排名和並排顯示

Type Cono Value 
1  100 66.5 
1  123 65.6 
1  145 56.8 
2  145  6 
2  100  7 
2  123  8 

所需的輸出:

Rank Cono A-value Rank Cono B-value 
1  100  66.5 1  123  8 
2  123  65.6 2  100  7 
3  145  56.8 3  145  6 

這是我試過,如果

;with cte as 
(
    select ROW_NUMBER() over(partition by type order by value desc) Rank,* 
    from temp1 
) 



select 
max(CASE when Rank = 1 then rank end) as 'Rank', 
max(CASE when Rank = 1 then cono end) as 'Cono', 
max(CASE when Rank = 1 then display_value end) as 'A-days', 
max(CASE when Rank = 2 then cono end) as 'Rank', 
max(CASE when Rank = 2 then cono end) as 'cono' 
max(CASE when Rank = 2 then display_value end) as 'B-days' 

from cte 
group by RANK,cono,value 

回答

1

不知道我的理解正確的,因爲它似乎是期望的輸出不對應樣本數據,所以我可能會錯過一些東西;但是這個查詢或者一個非常相似的查詢應該可以工作:

select t1.rank, t1.Cono, t1.value 'A-value', t2.rank, t2.Cono, t2.value 'B-value' 
from 
(select *,row_number() over (order by value desc) rank from temp1 where type=1) t1 
join 
(select *,row_number() over (order by value desc) rank from temp1 where type=2) t2 
on t1.rank=t2.rank 
+0

謝謝!抱歉數據混亂 - 我糾正了它。 – stackuser