当我想选择作者和阅读的书数时。我将使用以下语句

select authorid, count(authorid)
from books
where read = 1
group by authorid


当我想为给定作者选择未读书籍的数量时,我将在上面的语句中将1更改为0

我想为每个authorid选择比率unread/all,然后从所有这些比率中选择authoridmax(unread/all)

我可以创建这样的声明吗?最大比率为1。如果还有更多具有最大比例的authorid(例如,比例= 1),则可以将它们全部返回,随机返回或限制为1(这无关紧要)。

最佳答案

要获得所有比率,是这样的:

select authorid,
       SUM(case when read = 0 then 1 else 0 end)/count(authorid) as ratio
from books b
group by authorid




这将为您提供比例最大的产品:

select b.authorid, max(aux.ratio) as maxRatio
from books b
inner join(
    select authorid,
           SUM(case when read = 0 then 1 else 0 end)/count(authorid) as ratio
    from books b
    group by authorid) aux on b.authorid = aux.authorid
group by b.authorid

09-26 03:30