如果结果为空,则显示“0”

时间:2016-06-02 11:43:53

标签: sql

我尝试用SQL计算。计算结果显示在图表中。如果sql查询的结果为空,则图表停止工作:

这是我正在使用的SQL查询:

SELECT SUM(total) as total
FROM table
WHERE user_id = 1 AND date BETWEEN '2016-06-01' AND '2016-06-31'

如果表中有数据,则没有问题。当没有数据时,图表停止工作。

所以如果总数为空,我想显示'0'。如果它是空的,我需要在SQL查询中更改为显示“0”?

4 个答案:

答案 0 :(得分:3)

如果表为空,则使用COALESCE返回0而不是NULL:

SELECT COALESCE(SUM(total),0) as total
FROM table
WHERE user_id = 1 AND date BETWEEN '2016-06-01' AND '2016-06-31'

答案 1 :(得分:1)

你试过了吗?

SELECT ISNULL(SUM(total), 0) as total
FROM table
WHERE user_id = 1 AND date BETWEEN '2016-06-01' AND '2016-06-31'

答案 2 :(得分:0)

此查询将始终返回一行,如果没有匹配的行,则默认为零:

SELECT COALESCE((
  SELECT 
    SUM(total)
  FROM table
  WHERE user_id = 1 AND date BETWEEN '2016-06-01' AND '2016-06-31'
),0) AS total

答案 3 :(得分:0)

你可以试试这个:

if not exists (SELECT total FROM table WHERE user_id = 1 AND date BETWEEN '2016-06-01' AND '2016-06-31')
begin 
    select 0 as total
end
else
begin
    SELECT SUM(total) as total
    FROM table
    WHERE user_id = 1 AND date BETWEEN '2016-06-01' AND '2016-06-31'
end