用一些字符串替换NULL

时间:2015-08-03 15:56:31

标签: mysql

我的数据库中有一个表格,如下所示:

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

我希望在比较产品后显示结果:

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

运行以下查询后:

<pre>
SELECT  ProductName,
MAX(CASE 
WHEN Branch=1 
THEN Status
ELSE NULL 
END) AS 'Branch 1',
MAX(CASE 
WHEN Branch=2
THEN Status
ELSE NULL 
END) AS 'Branch 2'
FROM    MyTable
GROUP BY ProductName;

我得到的结果如下:

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

SQLFiddle
我想用OK替换NULL,但无法获得所需的结果。请指出我正确的方向。感谢

1 个答案:

答案 0 :(得分:3)

使用COALESCE()转义null

SELECT  ProductName,
      COALESCE(  MAX(CASE 
            WHEN Branch=1 
            THEN Status
            ELSE NULL 
        END) ,'OK') AS 'Branch 1',
       COALESCE( MAX(CASE 
            WHEN Branch=2
            THEN Status
            ELSE NULL 
        END),'OK') AS 'Branch 2'
FROM    MyTable
GROUP BY ProductName;

DEMO