在排名表上旋转

时间:2019-05-29 04:05:32

标签: sql sql-server

仅当等级为1或更高时,才尝试有效地将在分区列上具有等级的现有表转换为柱状。这是我的数据:

   -------------------------------------
   | Id | Value  | Name          | rank|
   -------------------------------------
   | 1  | 1234   | John          |1    |
   | 2  | 3456   | John          |2    |
   | 3  | 9999   | Chris         |1    |
   | 4  | 9801   | Joe           |1    | 
   | 5  | 1287   | Joe           |2    |
   _____________________________________

我要达到的目标:

   -------------------------------------
   |       ValA  | ValB     | Name     | 
   -------------------------------------
   | 1  | 1234   | 3456    | John      |
   | 2  | 9801   | 1287    | Joe       |
   -------------------------------------

尝试了几种版本的数据透视表,但我感觉缺少一些东西。关键是删除行仅1的行,如果我有1和2,则将其转换。

2 个答案:

答案 0 :(得分:0)

您可以在下面尝试-

select rank, name, max(case when rank=1 then value end) as valA,
max(case when rank=2 then value end) as valB
from
(
select * from tablename
where rank in (1,2)
group by id, value, name, rank
having count(distinct rank)=2
)X group by rank, name

答案 1 :(得分:0)

这是您想要的吗?

select max(case when rank = 1 then value end) as value_a,
       max(case when rank = 2 then value end) as value_b,
       name
where rank in (1, 2)
group by name
having count(*) = 2;

如果还需要第一列,只需添加row_number() over (order by (select null))