在SQLite中选择具有最大未读书籍百分比的作者

时间:2012-02-24 10:24:55

标签: sql sqlite

当我想选择作者和阅读的书籍数量时。我将使用以下声明

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

当我想为给定作者选择未读书籍的数量时,我会在上述声明中将1更改为0

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

我可以创建这样的声明吗?最大比率为1。如果有更多authorid s的最大比率(例如比率= 1),您可以返回所有这些,随机的或限制为1(这无关紧要)。

2 个答案:

答案 0 :(得分:3)

获得所有比率是这样的:

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

答案 1 :(得分:1)

我无法测试此ATM,但请尝试此

SELECT authorid, SUM(read) / COUNT(*)
FROM books
GROUP BY authorid
ORDER BY SUM(read) / COUNT(*) DESC

这应列出所有权利人以及比率。