考虑以下 Postgresql 数据库表:
id | book_id | author_id
---------------------------
1 | 1 | 1
2 | 2 | 1
3 | 3 | 2
4 | 4 | 2
5 | 5 | 2
6 | 6 | 3
7 | 7 | 2
在这个例子中,作者 1 写了 2 本书,作者 2 写了 4 本书,作者 3 写了 1 本书。我如何确定作者使用 SQL 编写的平均书籍数量?换句话说,我试图得到,“一个作者平均写了 2.3 本书”。
到目前为止,我对 AVG 和 COUNT 的尝试都失败了。有什么想法吗?
最佳答案
select avg(totalbooks) from
(select count(1) totalbooks from books group by author_id) bookcount
我认为您的示例数据实际上只有作者 ID 为 2 的 3 本书,所以这不会返回 2.3
http://sqlfiddle.com/#!15/3e36e/1
第四本书:
关于sql - 你如何确定Postgresql中一列的平均总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20387938/