根据要过滤的列的值进行连接和分组

问题描述 投票:0回答:2

假设我有两个包含这些数据的表:

author
id | name
---------
1  | John
2  | Jack
3  | James
4  | Bob
5  | Gorge

book
id | author_id | title  | state
-------------------------------------
1  | 1         | book_1 | published
2  | 1         | book_2 | pre-published
3  | 1         | book_3 | published
4  | 1         | book_4 | rejected
5  | 2         | book_5 | published
6  | 3         | book_6 | rejected
7  | 3         | book_7 | pre-published
8  | 4         | book_8 | rejected

我想要的是一个sql查询,它可以给我每个作者的id、姓名和出版书籍的数量,即使他们出版了0本。我认为这可能是一个简单的查询,但我坚持了下来,我想要的是:

id | name   | num_of_published_books
------------------------------------
1  | John   |          2
2  | Jack   |          1
3  | James  |          0
4  | Bob    |          0
5  | Gorge  |          0

我能够获取前两行

John
Jack
。我还可以根据
author_id
state
对它们进行分组。但这不是我想要的。

请注意,我不想使用子查询。

sql postgresql group-by count
2个回答
0
投票
SELECT
  a.id AS author_id,
  a.name,
  COUNT(b.state = 'published' OR NULL) AS num_of_published_books
FROM
  author a
LEFT JOIN
  book b ON a.id = b.author_id
GROUP BY
  a.id, a.name;

希望对您有帮助。


0
投票
SELECT author.id, author.name, 
       COALESCE(COUNT(CASE state  
                         WHEN 'published' THEN 1 
                         ELSE O 
                      END), 0)) as num_of_published_books
FROM   author
       LEFT OUTER JOIN book
          ON author.id = book.author_id
GROUP BY author.id, author.name
© www.soinside.com 2019 - 2024. All rights reserved.