在mysql中将列转换为行交叉表

时间:2013-06-06 07:34:36

标签: mysql

我想在MySQL中创建交叉表。

有两个表TABL1和TBL2,我不知道如何将列转换为行。

请给我一个解决方案。

我的编码如下:

选择*来自TBL1 t1左连接TBL2 t2 on t1.des = t2.des;

TBL1 :
DES
A
C
D
E

TBL2
ID DES
1  A
2  C
3

RESULT THAT I NEED

ID   A   C  D  E
1    1
2        1
3

此致

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
    t2.id,
    SUM(IF(t1.des IS NOT NULL AND t1.des = 'A',1,0)) as 'A',
    SUM(IF(t1.des IS NOT NULL AND t1.des = 'C',1,0)) as 'C',
    SUM(IF(t1.des IS NOT NULL AND t1.des = 'D',1,0)) as 'D',
    SUM(IF(t1.des IS NOT NULL AND t1.des = 'E',1,0)) as 'E'
FROM
    TBL2 t2
LEFT JOIN TBL1 t1
    ON t2.des = t1.des
GROUP BY
    t2.id

答案 1 :(得分:0)

对于某些自动化,您可以尝试使用后续步骤:

  1. 制作一个光标来读取你的TBL1 - 这样你就会知道你有多少cols

    DECLARE curs CURSOR FOR SELECT des FROM TBL1;
    
  2. 在游标内部,您需要为Select语句创建dynamicSQL。像这样:

    ....
    FETCH curs INTO cDes;
    ....
    set @sel = concat(@sel, 
    ', SUM(IF(t1.des IS NOT NULL AND t1.des = ''', cDes,''',1,0)) as ''',cDes, '''');
    ...
    CLOSE curs;
    
  3. 完成后,您需要完成动态SQL的完整版本。像这样的东西:

    set @crosstab = concat('select t2.id', @sel, 
                            'FROM TBL2 t2
                            LEFT JOIN TBL1 t1 ON t2.des = t1.des
                            GROUP BY t2.id');
    
    PREPARE STMT FROM @crosstab;
    EXECUTE STMT;
    DEALLOCATE PREPARE STMT;