如何编写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
答案 0 :(得分: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