我有一个SQL查询:

select task_id, count(status) as not_paided
        from some_table
        where status = 'not_paid' and task_id = 34
        group by task_id

如果没有not_paid行,它应该返回34/0(task_id/not_paided),但它不返回任何内容。我不知道该怎么办,已经试过casecoalesce

最佳答案

34/0不可能,因为此where子句没有行。
如果你真的需要它,你需要一个子查询。像这样的人:

select
    main.task_id,
    (select count(sub.status)
     from some_table as sub
     where sub.status = 'not_paid'
     and sub.tast_id = main.task_id) as not_paided
from some_table as main
where main.task_id = 34

编辑:
另一种方法是使用一个简单的case when
select
    task_id,
    sum(case when status = 'not_paid' then 1 else 0 end) as not_paided
from some_table
where task_id = 34
group by task_id

10-07 18:53
查看更多