我有一个相当困难的查询。 我需要在名为' key_phrases'的表上写一个查询。 (列:'用户','词组' tfw'),它检索每个用户的前10%行,其中列的值最高&# 39; TFW&#39 ;.该查询应返回所有列。 提前谢谢,Nil
答案 0 :(得分: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