首页 > 解决方案 > 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
...
..
..

尽管我尝试了各种导致错误的选项,但我无法按要求得到。

标签: mysqlsqlgroup-bypivot

解决方案


对于固定的样本 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

推荐阅读