我被困在一個應該很簡單的問題上。假設我有兩個表:authors和books。對于這個例子,我們假設一本書只有一個作者。我想要一份報告,表達作者寫了 x 本書的數量,例如:
| 書數 | 數量 |
|---|---|
| 0 | 3 |
| 1 | 10 |
| 2 | 15 |
...
問題是,當我(外部)加入書籍和作者時,我會獲得NULL書籍的價值。
我最好的方法是在兩個查詢中完成它,一個帶有一個,inner join所以我排除了尚未寫過一本書的作者,然后我以編程方式添加它們的計數。
這是我的查詢
select
book_count,
count(*)
from (
select
a.id,
count(*) as book_count
from authors a
join books b
on a.id = b.author_id
group by a.id
) a
group by book_count
如何僅在一個查詢中執行此操作?
編輯:這是一個最小的例子
create table authors (
id int primary key,
name varchar(100)
);
create table books (
id int primary key,
title varchar(255),
author_id int
);
insert into authors values
(1, 'Isaac Asimov'),
(2, 'Ray Bradbury'),
(3, 'Aldous Huxley'),
(4, 'Bruno Dusausoy');
insert into books values
(1, 'Foundation', 1),
(2, 'Foundation and Empire', 1),
(3, 'Second Foundation', 1),
(4, 'Fahrenheit 451', 2),
(5, 'Brave New World', 3);
使用上面提到的查詢,我沒有得到該行 0, 1
| 書數 | 數數 |
|---|---|
| 3 | 1 |
| 1 | 2 |
如果我做一個left join我得到
| 書數 | 數數 |
|---|---|
| 3 | 1 |
| 1 | 3 |
所以NULL不一樣0
uj5u.com熱心網友回復:
把書留給作者怎么樣。
那么沒有書籍的作者將有一個 0 book_count。
select book_count, count(*) as amount from ( select author.id as author_id, count(book.id) as book_count from authors as author left join books as book on book.author_id = author.id group by author.id ) a group by book_count order by book_count
| 書數 | 數量 |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 3 | 1 |
db<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380940.html
標籤:sql PostgreSQL的
