sql server—在sql中透视表,并保留原始表中的某些列

dgenwo3n  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(431)

这个问题在这里已经有答案了

获取列中的前6项以透视到sql中的行(1个答案)
需要动态数据透视,行号为()(1个答案)
11个月前关门了。
我有以下格式的数据:

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 在结果表中。另外,在创建数据透视列时,我希望确保只拾取固定列。例如,如果rank threshold为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.

有没有一种方法可以通过SQLServer实现这一点?

5ssjco0h

5ssjco0h1#

用下列方法尝试 case 声明,这是演示。

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#  |

相关问题