如何消除相同行的重复

时间:2015-07-28 07:47:02

标签: 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(
  'GROUP_CONCAT(case when branch = ''',
  branch,
  ''' then status ELSE NULL end) 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,dead |
| p2          | expired | (null)    |
+-------------+---------+-----------+

SQL Fiddle
我现在想要的是将产品状态显示为" OK"当状态为null时,不是null,如果表中有重复的产品,也不需要连接状态..很多但是无法解决。提前谢谢。

1 个答案:

答案 0 :(得分:2)

这有点棘手,因为如果状态相同会有重复,因此合并必须在GROUP_CONCAT的外部

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;

Link