gpt4 book ai didi

mysql - SQL 选择前 n% 行

转载 作者:行者123 更新时间:2023-11-29 02:24:24 25 4
gpt4 key购买 nike

我有一个相当困难的问题。我需要在名为“key_phrases”(列:“user”、“phrase”、“tfw”)的表上编写一个查询,该表检索每个用户的前 10% 行,这些行具有列“tfw”的最高值。查询应返回所有列。提前致谢,无

最佳答案

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

关于mysql - SQL 选择前 n% 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25549172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com