如何将存储过程转换为单个SQL语句

时间:2015-08-02 19:19:22

标签: mysql

我的数据库中有一个表格(表格中可能有相同的元组):

+-------------+---------+--------+
| ProductName | Status  | Branch |
+-------------+---------+--------+
| P1          | dead    |      1 |
| P1          | dead    |      2 |
| P1          | dead    |      2 |
| P2          | expired |      1 |
+-------------+---------+--------+

我必须在as之后显示结果(Branch属性是动态的):

+-------------+---------+--------+
| ProductName | Branch 1|Branch 2|
+-------------+---------+--------+
| P1          | dead    |    dead|
| P2          | expired |     OK |
+-------------+---------+--------+

经过一些帮助,我提出了以下解决方案:

    SET @sql = NULL;
    SELECT
    GROUP_CONCAT(DISTINCT
       CONCAT(
       'COALESCE(GROUP_CONCAT(DISTINCT case when branch = ''',
       branch,
       ''' then  status  end),''OK'') AS ',
       CONCAT('Branch',branch)
       )
    ) INTO @sql
    FROM Table1;

    SET @sql = CONCAT('SELECT productName, ', @sql, ' 
    FROM Table1 
    GROUP BY productName');

    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    

它显示了我需要的确切结果:

+-------------+---------+-----------+
| productName | Branch1 |  Branch2  |
+-------------+---------+-----------+
| p1          | dead    |    dead   |
| p2          | expired |    OK     |
+-------------+---------+-----------+

SQL Fiddle

我希望将此过程转换为单个SQL语句。我试过但找不到解决方案。我怎样才能实现这一目标?感谢

1 个答案:

答案 0 :(得分:0)

这个确切的结果(因为它是由存储过程产生的,在运行时确定的列数)不能在单个SQL select语句中重现。这是不可能的。