mysql - Mysql如何获取与其他列组合的列
问题描述
我有一张这样的桌子
+------+------+----------+
| X | Y | SAMPLE_id |
+------+------+----------+
| 1.0 | 10 | 1 |
| 1.0 | 20 | 2 |
| 1.0 | 30 | 3 |
| 1.0 | 40 | 4 |
| 2.0 | 25 | 1 |
| 2.0 | 26 | 2 |
| 2.0 | 27 | 3 |
| 2.0 | 28 | 4 |
| 3.0 | 35 | 1 |
| 3.0 | 35 | 2 |
| 3.0 | 35 | 3 |
| 3.0 | 35 | 4 |
| 4.0 | 50 | 1 |
| 4.0 | 50 | 2 |
| 4.0 | 50 | 3 |
| 4.0 | 50 | 4 |
| 5.0 | 65 | 1 |
| 5.0 | 65 | 2 |
| 5.0 | 65 | 3 |
| 5.0 | 65 | 4 |
**我需要这样显示**
X Y_SAMPLE_ID_1 Y_SAMPLE_ID_2 Y_SAMPLE_ID_3 Y_SAMPLE_ID_4
1 10 20 30 40
2 25 26 27 28
...
..
..
尽管我尝试了各种导致错误的选项,但我无法按要求得到。
解决方案
对于固定的样本 id 列表,您可以进行条件聚合:
select
x,
max(case when sample_id = 1 then y end) y_sample_id_1,
max(case when sample_id = 2 then y end) y_sample_id_2,
max(case when sample_id = 3 then y end) y_sample_id_3,
max(case when sample_id = 4 then y end) y_sample_id_4
from mytable
group by x
推荐阅读
- encryption - 如何在 Salesforce 中安全地存储加密密钥?
- ios - Xcode 网页视图。在 Safari 中打开 target="_blank" 链接
- bash - 这些 Bash 间接方法有什么区别?
- python - Python正则表达式:检测包含特定单词的模式?
- r - 在每个滚动中添加一个 selectInput 并计算选择选项之间的时间
- ubuntu - 我无法在同一台服务器下 ping 域,但可以从其他机器
- lua - 当我使用“for”填充它时,我在 lua 中的表只打印 nil
- python - 熊猫按时间顺序重复行
- amazon-web-services - RethinkDB 与 i3.Metal 实例上的 1.5k 写入作斗争
- c++ - QWidget move() 和 QGraphicsOpacityEffect 导致黑色边框