如何在计数中显示0?

时间:2014-11-02 03:37:21

标签: sqlite

如果没有资格匹配,如何显示0?

我目前的查询是:

select s.sname, count(*) as number
from sailor s, boat b
where s.rating >= b.rating
group by s.sname
order by number desc;

我得到的结果是:

a  3
b  3
c  2

然而,这并不是我想要实现的目标。我想显示如下结果:

a 3
b 3
c 2
d 0
e 0

我尝试将计数()更改为isnull(count(),0)或coalesce(count(*),0)但在这种情况下它不会更正。

CREATE TABLE sailor (
    sname   character varying primary key,
    rating  integer
);

create table boat (
    bname   character varying primary key,
    color   character varying,
    rating  integer
);

2 个答案:

答案 0 :(得分:1)

这可能对您有所帮助

select s.sname,(select count(*) 
from boat b
where s.rating >= b.rating
) t
from sailor s
order by t desc;

SQLFIDDLE

答案 1 :(得分:1)

您正在使用内部联接,当两个表中的数据匹配时,它只返回行。

要返回没有任何匹配船只的水手,请使用outer join

select s.sname, count(*) as number
from sailor s
left join boat b on s.rating >= b.rating
group by s.sname
order by number desc;