使用SQL转换表 - 行作为列

时间:2018-05-26 11:49:47

标签: mysql sql select

我有下表:

sample_name gene_name expression_value 
Father 1    A1BG       1.53462 
Q83X 1      A1BG       1.29403 
Rescue 1    A1BG       1.81678 
Father 2    A1BG       1.56481 
Q83X 2      A1BG       0.924723 
Rescue 2    A1BG       1.70408 
Father 1    A1BG-AS1   1.96224 
O83X 1      A1BG-AS1   1.92807 
Rescue 1    A1BG-AS1   2.0421 
Father 2    A1BG-AS1   1.61606

我想编写一个生成以下输出的选择查询:

Gene     Father_1 Father_2 Q83X_1     Q83X_2    Rescue_1   Rescue_2
A1BG     1.53462  1.56481  1.29403    0.924723  1.81678    1.70408
A1BG-AS1 ......     .....   .....      .........  .......    ........

我如何实现这一目标?

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用以下方法在MySQL中执行Pivot:

mysql> create table tabx_1(sample_name varchar(200),gene_name varchar(200),expression_value float);
Query OK, 0 rows affected (0.46 sec)

mysql> insert into tabx_1 values
    -> ('Father 1','A1BG','1.53462'), 
    -> ('Q83X 1','A1BG','1.29403'), 
    -> ('Rescue 1','A1BG','1.81678'), 
    -> ('Father 2','A1BG','1.56481'), 
    -> ('Q83X 2','A1BG','0.924723'), 
    -> ('Rescue 2','A1BG','1.70408'), 
    -> ('Father 1','A1BG-AS1','1.96224'), 
    -> ('O83X 1','A1BG-AS1','1.92807'), 
    -> ('Rescue 1','A1BG-AS1','2.0421'), 
    -> ('Father 2','A1BG-AS1','1.61606');
Query OK, 10 rows affected (0.08 sec)
Records: 10  Duplicates: 0  Warnings: 0

mysql> 
mysql> select gene_name,
    -> sum(case sample_name when 'Father 1' then expression_value end) Father_1,
    -> sum(case sample_name when 'Father 2' then expression_value end) Father_2,
    -> sum(case sample_name when 'Q83X 1' then expression_value end) Q83X_1,
    -> sum(case sample_name when 'Q83X 2' then expression_value end) Q83X_2,
    -> sum(case sample_name when 'Rescue 1' then expression_value end) Rescue_1,
    -> sum(case sample_name when 'Rescue 2' then expression_value end) Rescue_2
    -> from tabx_1
    -> group by gene_name;
+-----------+--------------------+--------------------+-------------------+--------------------+--------------------+--------------------+
| gene_name | Father_1           | Father_2           | Q83X_1            | Q83X_2             | Rescue_1           | Rescue_2           |
+-----------+--------------------+--------------------+-------------------+--------------------+--------------------+--------------------+
| A1BG      | 1.5346200466156006 |  1.564810037612915 | 1.294029951095581 | 0.9247230291366577 | 1.8167799711227417 | 1.7040799856185913 |
| A1BG-AS1  | 1.9622399806976318 | 1.6160600185394287 |              NULL |               NULL |  2.042099952697754 |               NULL |
+-----------+--------------------+--------------------+-------------------+--------------------+--------------------+--------------------+
2 rows in set (0.00 sec)