我需要替换所有等于NULL值“ 0”的可能结果。 最好的选择是什么?在这种情况下,请使用case语句或replace命令:
SELECT name, COUNT(IF(stat='open',1, NULL)) 'open',
COUNT(IF(stat='close',1, NULL)) 'close',
COUNT(IF(stat='all',1, NULL)) 'all',
COUNT(IF(stat='reopen',1, NULL)) 'reopen',
COUNT(IF(stat='finish',1, NULL)) 'finish'
FROM dashboard group by name order by name = 'Party' desc
+----------+------+-------+-----+--------+--------+
| name | open | close | all | reopen | finish |
+----------+------+-------+-----+--------+--------+
| Party | 21 | 0 | 0 | 0 | 0 |
+----------+------+-------+-----+--------+--------+
答案 0 :(得分:2)
您可以使用NULLIF()
功能。
SELECT name,
NULLIF(COUNT(IF(stat='open',1, NULL)), 0) 'open',
NULLIF(COUNT(IF(stat='close',1, NULL)), 0) 'close',
NULLIF(COUNT(IF(stat='all',1, NULL)), 0) 'all',
NULLIF(COUNT(IF(stat='reopen',1, NULL)), 0) 'reopen',
NULLIF(COUNT(IF(stat='finish',1, NULL)), 0) 'finish'
FROM dashboard
group by name
order by name = 'Party' desc
NULLIF()
返回第一个值,除非它等于第二个值,然后返回NULL
。
顺便说一句,您可以将COUNT(IF(stat='xxx', 1, NULL))
简化为SUM(stat='xxx')
。
答案 1 :(得分:1)
一种方法使用NULLIF()
:
SELECT name,
NULLIF(SUM(stat = 'open'), 0) as open,
NULLIF(SUM(stat = 'close'), 0) as close,
NULLIF(SUM(stat = 'all'), 0) as all,
NULLIF(SUM(stat = 'reopen'), 0) as reopen,
NULLIF(SUM(stat = 'finish'), 0) as finish
FROM dashboard
GROUP BY name
ORDER BY name = 'Party' desc;
另一个人使用CASE
:
SELECT SUM(CASE WHEN stat = 'open' THEN 1 END) as open,
. . .