2012-02-24 37 views
1

当我想选择作者和阅读的书籍数量时。我会用下面的语句在SQLite中选择具有最大未读书籍百分比的作者

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

当我要选择的未读的书籍数量对于一个给定的作者,我会在上面的语句更改10

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

我可以创建这样一个语句吗?最大比率是1。如果有更多的authorid s,最大比例(例如ratio = 1),你可以将它们全部返回,随机选择或限制为1(这并不重要)。

回答

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 
+0

第一个陈述很好。我不知道这个有条件的计数。但第二个陈述不会只选择最大比率。 – xralf 2012-02-24 10:55:57

+0

该解决方案是正确的。我使用'按比例排序'的第二个'select'语句的语法。 – xralf 2012-02-24 11:33:55

+1

但是在分割表达式中需要使用'cast(count(authorid)as float)'。 – xralf 2012-02-24 12:01:22

1

我不能对此进行测试ATM,但试试这个

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

这应当列出所有authorids配合比一起。

+0

这会给出错误的比例。检查问题。 – 2012-02-24 10:37:36

+0

@aF。我做到了,对我来说仍然看起来像是0/1场; ) – 2012-02-24 10:42:26

+0

他想要UNREAD比率。你的'SUM(读)'将使READ比率,因为当作者读这本书时读= 1,否则为0。得到它了? – 2012-02-24 10:46:29