2014-08-28 91 views
2

我有一個相當困難的查詢。 我需要在一個名爲'key_phrases'(列:'user','phrase','tfw')的表上寫一個查詢,它爲每個用戶檢索前10%的行,列'tfw' 。查詢應該返回所有列。 由於事先無SQL Select Top n percent rows

+0

什麼datapye包含列「FTW」?這一列的含義究竟是什麼?是否有任何示例值可用? – reporter 2014-08-28 12:47:52

+0

ftw(float)的值:0.00473934, 0.00173913 – user3628777 2014-08-28 13:00:40

回答

2
select user, phrase, tfw 
from key_phrases t1 
join (
    select count(*) total_rows_per_user, user 
    from key_phrases 
    group by user 
) t2 on t1.user = t2.user 
where (
    select count(*) from key_phrases t3 
    where t3.user = t1.user 
    and t3.tfw >= t1.tfw 
)/total_rows_per_user <= .1 

使用變量另一個查詢應該是更快

select user, phrase, tfw, 
if(@prev_user = user, @user_count := @user_count + 1, @user_count := 1), 
@prev_user := user 
from key_phrases t1 
join (
    select count(*) total_rows_per_user, user 
    from key_phrases 
    group by user 
) t2 on t1.user = t2.user 
cross join (select @user_count := 1, @prev_user := null) t3 
where @user_count/total_rows_per_user >= .9 
order by user, tfw 
+0

很好,謝謝。非常感激 – user3628777 2014-08-28 13:39:35