2

代码:

SELECT 
  count(*) as count, 
  sum(Status = 'test1') as count_test1, 
  sum(Status = 'test2') as count_test2
FROM Table
WHERE Type = 'test'

结果我看到:

count   count_test1   count_test2
  0       NULL           NULL

请告诉我,是否有可能使显示 0 而不是 NULL?

PS:结果是:

count   count_test1   count_test2
  0       0               0
4

3 回答 3

4

您可以使用COALESCE

COALESCE(sum(Status = 'test1'), 0)

或者IFNULL

IFNULL(sum(Status = 'test1'), 0)
于 2013-10-14T11:34:12.367 回答
1
SELECT 
  count(*) as count, 
      IFNULL(sum(Status = 'test1'), 0) as count_test1, 
      IFNULL(sum(Status = 'test2'), 0) as count_test2
FROM Table
WHERE Type = 'test'
于 2013-10-14T11:36:46.123 回答
0

您可以使用COALESCE接受数组并返回第一个元素不为空的函数

SELECT 
  count(*) as count, 
  COALESCE(sum(Status = 'test1'), 0) as count_test1, 
  COALESCE(sum(Status = 'test2'), 0) as count_test2
FROM Table
WHERE Type = 'test'
于 2013-10-14T11:37:42.737 回答