MySQL 行转列

快来打我* 2022-01-28 23:17 369阅读 0赞

假如有一个成绩表tom,如下

  1. mysql> select * from tom;
  2. +------+---------+-------+
  3. | name | subject | score |
  4. +------+---------+-------+
  5. | sam | english | 100 |
  6. | sam | math | 100 |
  7. | sam | chinese | 99 |
  8. +------+---------+-------+
  9. 3 rows in set (0.00 sec)

需要在一行中显示各科成绩,以分步分析:
1.

  1. mysql> select name,
  2. -> case subject when 'english' then score else 0 end 'english',
  3. -> case subject when 'math' then score else 0 end 'math',
  4. -> case subject when 'chinese' then score else 0 end 'chinese'
  5. -> from tom;
  6. +------+---------+------+---------+
  7. | name | english | math | chinese |
  8. +------+---------+------+---------+
  9. | sam | 100 | 0 | 0 |
  10. | sam | 0 | 100 | 0 |
  11. | sam | 0 | 0 | 99 |
  12. +------+---------+------+---------+
  13. 3 rows in set (0.00 sec)
  1. mysql> select name,

    1. -> max(case subject when 'english' then score else 0 end) 'english',
    2. -> max(case subject when 'math' then score else 0 end) 'math',
    3. -> max(case subject when 'chinese' then score else 0 end) 'chinese'
    4. -> from tom group by name;

    +———+————-+———+————-+
    | name | english | math | chinese |
    +———+————-+———+————-+
    | sam | 100 | 100 | 99 |
    +———+————-+———+————-+
    1 row in set (0.00 sec)

发表评论

表情:
评论列表 (有 0 条评论,369人围观)

还没有评论,来说两句吧...

相关阅读

    相关 MySQL

    离恨恰如春草,更行更远还生 先看结果: ![这里写图片描述][70] 把上面一个字段,里面的每个数据都是用逗号分隔的,把它变成下面这样: ![这里写图片描述][