sql - 在 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 实现这一点?
解决方案
试试下面的 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# |
推荐阅读
- raspberry-pi - 我们如何通过键盘在树莓派中选择 wifi
- java - 错误的屏幕宽度返回 javaFX
- nativescript - Nativescript 音视频通道
- javascript - 填充对象中的字段,来自其他对象
- node.js - Google API 重命名导入的变量会产生错误
- android - 在 ionic cordova 中构建到 android 时出现错误
- multithreading - 如何让一个线程等待另一个线程完成使用 OpenMP 线程?
- typescript - 为什么 Typescript 不会错误泛型联合类型?
- c - 为什么在这种情况下会发生分段错误?Openmp 问题
- php - mysqli insert 在上传大文件时不起作用