postgresql 如何计算平均数并给予子查询标签

zqdjd7g9  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(2)|浏览(136)

我有两个表“book”和“authorCollection”。因为一本书可能有多个作者,我希望得到2000年(含)后出版的“书”表中作者的平均数量。例如:

Table Book:
key  year
1     2000
2     2001
3     2002
4     1999

Table authorCollection:
key author
1    Tom
1    John
1    Alex
1    Mary
2    Alex
3    Tony
4    Mary

结果应该是(4 + 1 + 1)/ 3 = 2;(关键词4在2000年之前出版)。我写了下面的查询语句,但是不对,我需要在子查询中得到结果的个数,但是不能给予它一个标签“b”,我该怎么解决这个问题呢?#21453;,平均作者数?我仍然对“COUNT(*)as count”的意思感到困惑......谢谢。

SELECT  COUNT(*) as count,  b.COUNT(*) AS total 
FROM A
WHERE key IN  (SELECT key
               FROM Book
               WHERE year >= 2000
               ) b
GROUP BY key;
krcsximq

krcsximq1#

首先,计算子查询中keyauthors数量。接下来,聚合所需的值:

select avg(coalesce(ct, 0))
from book b
left join (
    select key, count(*) ct
    from authorcollection
    group by 1
    ) a
using (key)
where year >= 2000;
o4hqfura

o4hqfura2#

示例以及处理“除以零”错误:

select case when count(distinct book.key)=0
  then null
  else count(authorCollection.key is not null)/count(distinct book.key)
  end as avg_after_2000
from book
left join authorCollection on(book.key=authorCollection.key)
where book.year >= 2000

相关问题