0

我想在 MySQL 中创建交叉表。

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

请给我一个解决方案。

我的编码如下:

select * from TBL1 t1 left join 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

问候,

4

2 回答 2

0

对于一些自动化,您可以尝试使用以下步骤:

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

    DECLARE curs CURSOR FOR SELECT des FROM TBL1;
    
  2. 在游标内,您需要为 Select 语句创建一个动态 SQL。像这样的东西:

    ....
    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. 完成后,您需要完成一个完整版本的 dynamicSQL。像这样的东西:

    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;
    
于 2013-06-07T10:54:52.203 回答
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
于 2013-06-06T07:40:02.010 回答