找出每个D的总点数,如果P中没有D,则点数应为0

时间:2018-11-05 17:22:40

标签: sql postgresql

我想找到每个D的总点数。 如果P中没有D的实例,则这些点应返回为0。 我的表是:

P 
code (referencing D.id), c_code (referencing C.id)

D
id, name

C
id
name
points

我的查询是:

SELECT D.id, SUM(C.points)
FROM D JOIN P ON D.id=P.code JOIN C ON P.c_code=C.id
GROUP BY D.id
HAVING CASE WHEN D.id NOT IN (SELECT *
                               FROM P p1
                               WHERE p1.code=D.id) THEN '0' end;

2 个答案:

答案 0 :(得分:2)

您需要外部联接来获得不匹配的行,再加上coalesce以返回零而不是NULL:

SELECT D.id, coalesce(SUM(C.points), 0)
FROM D LEFT JOIN P ON D.id=P.code
LEFT JOIN C ON P.c_code=C.id
GROUP BY D.id

答案 1 :(得分:1)

您可以使用外部联接,如下所示:

select
    d.id, sum(c.points)
  from d
  left join p on p.code = d.id
  left join c on c.id = p.c_code
  group by d.id