› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
icemanpro
V2EX  ›  MySQL

如何将下表转换成列显示?

  •  
  •   icemanpro · Jun 1, 2018 · 3377 views
    This topic created in 3042 days ago, the information mentioned may be changed or developed.
    | tpname | level | name |
    |--------|-------|------|
    | tp1 | 1 | a |
    | tp1 | 2 | b |
    | tp1 | 3 | c |
    | tp2 | 1 | d |
    | tp2 | 1 | e |


    转换成

    | tpname | level1 | level2 | level3 |
    |--------|--------|--------|--------|
    | tp1 | a | b | c |
    | tp2 | d | e | |


    sql 语句应该如何写?
    Supplement 1  ·  Jun 1, 2018
    已解决

    drop table tb;
    create TEMPORARY table tb(tpname varchar(10),`level` int,`name` varchar(10));

    insert into tb
    VALUES('tp1',1,'a'),('tp1',2,'b'),('tp1',3,'c'),('tp2',1,'d'),('tp2',2,'e');

    select tpname,GROUP_CONCAT(level1) as aa,GROUP_CONCAT(level2) as bb,GROUP_CONCAT(level3) as cc from (
    select tpname,
    case when `level`=1 then name end as level1,
    case when `level`=2 then name end as level2,
    case when `level`=3 then name end as level3
    from tb a
    ) as dd
    GROUP BY tpname
    1 replies  •  2018-06-01 10:53:25 +08:00
    arnoldFu
        1
    arnoldFu  
       Jun 1, 2018
    oracle 可以使用 pivot 动态生成列,mysql 不知道有没有,或者使用存储过程创建视图来做
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3878 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 05:33 · PVG 13:33 · LAX 22:33 · JFK 01:33
    ♥ Do have faith in what you're doing.