2016-12-28 80 views

回答

0

也許你可以使用自定義sql查詢結合find_by_sql

自定義的SQL查詢,然後可以看看如下:

select * from subscription 
where id in (
    select u1.subscription 
    from usertodo u1 
    group by u1.subscription 
    having 
    (select count(*) 
    from usertodo u2 
    where u2.subscription = u1.subscription 
     and u2.completed = true) >= 0.50 * count(*) 
) 

查詢假定下面的架構。當然,你的模式將與此不同。但結構可能是相同的。我已經在MySQL 5.6中測試了這個查詢(但是沒有使用Active Records,因爲設置環境本來會有很多工作)。希望能幫助到你!

create table subscription (
    id int, 
    name varchar(50) 
); 

insert into subscription (id, name) values 
    (1, "should be below 50 percent"), (2, "should be above 50 percent"); 

create table usertodo (
    subscription int, 
    completed bool 
); 

    insert into usertodo (subscription, completed) values 
    (1, true),(1,false),(1,false),(2,true),(2,true),(2,false);