Postgresql什么都没回来

时间:2015-02-18 06:31:14

标签: sql postgresql

我有这个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

1 个答案:

答案 0 :(得分:0)

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

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

sum
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