无行时返回0的计数

时间:2018-01-11 04:47:55

标签: sql oracle

好的,我已经看了这个并尝试了许多解决方案,但无法让它发挥作用。我有点像新手。这是我的原始查询 - 如果学生表中没有结果,如何让它为帐户返回0?

SELECT a.NAME
    ,count(s.student_sid)
FROM account a
JOIN inst i ON a.inst_sid = i.root_inst_sid
JOIN inst_year iy ON i.inst_sid = iy.inst_sid
JOIN student s ON iy.inst_year_sid = s.inst_year_sid
WHERE s.demo = 0
    AND s.STATE = 1
    AND i.STATE = 1
    AND iy.year_sid = 16
    AND a.account_sid IN (
        20187987
        ,20188576
        ,20188755
        ,52317128
        ,20189249
        )
GROUP BY a.NAME;

2 个答案:

答案 0 :(得分:3)

使用外部连接,将该表上的条件移动到连接中:

null

s.student_sid不计算student值,plt.subplots()如果没有行从Axes加入,则会ax

答案 1 :(得分:1)

您需要LEFT JOIN,然后SUM()覆盖s.student_sid不为空的群组:

select
    a.name,
    sum(case when s.student_sid is null then 0 else 1 end) as student_count
from account a
join inst i on a.inst_sid = i.root_inst_sid
join inst_year iy on i.inst_sid = iy.inst_sid
left join student s
    on iy.inst_year_sid = s.inst_year_sid
    and s.demo = 0
    and s.state = 1
where i.state = 1
and iy.year_sid = 16
and a.account_sid in (20187987, 20188576, 20188755, 52317128, 20189249)         
group by a.name;

这假设您要过滤的student表中的所有字段都是可选的。如果您不想强制删除记录,例如s.state不等于1,那么您需要将s.state=1谓词移到WHERE子句中。

如果由于某种原因,您获得了重复的学生ID并且学生被计算两次,那么您可以将聚合函数更改为:

count(distinct s.student_id) as student_count

...可以安全地执行count(distinct ...)忽略空值。

相关问题