请教一个经典的 postgres 的 sql 怎么写

37次阅读

共计 474 个字符,预计需要花费 2 分钟才能阅读完成。

现在有 2 张表:student 和 transactions

student 长这样:

id name
1 a
2 b
3 c

transactions

id student_id updated_at
1 1 2024-02-06T16:41:05+08:00
2 1 2024-02-06T13:41:05+08:00
3 2 2024-02-06T12:41:05+08:00

现在想在 postgres 里面用一个 sql,查出每个用户的 transaction 数量,并且把没有的多一行为 0。

SELECT s.id AS student_id, s.name, COUNT(t.id) AS transactions_count
FROM student s
LEFT JOIN transactions t ON s.id = t.student_id
GROUP BY s.id, s.name;

但是这样,查出来的结果是

student_id name transactions_count
1 a 2
2 b 1

但是我们需要查出的结果是

student_id name transactions_count
1 a 2
2 b 1
3 c 0

求教各位高手指点下这个 sql 怎么写。。。

正文完
 0