首页 > 解决方案 > 在 SQL 中透视表,保留原始表中的一些列

问题描述

我有以下格式的一些数据:

col1 | col2 | col3 | rank
--------------------------
  A  |  1   |  D1  | 1
  A  |  1   |  D2  | 2
  A  |  1   |  D3  | 3
  B  |  5   |  E!  | 1
  B  |  5   |  E@  | 2
  B  |  5   |  E#  | 3
  B  |  5   |  E$  | 4
  C  |  3   |  F1  | 1
  C  |  3   |  F2  | 2

我想通过 col3 旋转它,但想保留col1, col2结果表中的列。此外,在创建数据透视列时,我想确保只选择固定等级。例如,如果排名阈值为 3,则输出将如下所示:

col1 | col2  | P1  | P2 |  P3
------------------------------
  A  |  1    | D1  | D2 | D3
  B  |  5    | E!  | E@ | E#

解释:

1. In the output, the two rows with ``col1==C`` are dropped since they don't meet the rank threshold 3. 
2. The row with ``col3==E$`` is dropped since it's rank is higher than the rank threshold 3. 

有没有办法通过 SQL Server 实现这一点?

标签: sqlsql-serverpivot

解决方案


试试下面的 withcase语句,这里是演示

with cte as
(
  select
    col1,
    col2,
    max(case when rank = 1 then col3 end) as P1,
    max(case when rank = 2 then col3 end) as P2,
    max(case when rank = 3 then col3 end) as P3
  from myTable
  group by
    col1,
    col2
)

select 
    *
from cte
where P1 is not null and P2 is not null and P3 is not null

输出:

| col1 | col2 | p1  | p2  | p3  |
| ---- | ---- | --- | --- | --- |
| A    | 1    | D1  | D2  | D3  |
| B    | 5    | E!  | E@  | E#  |

推荐阅读