[英]How to query different group of data with SQL with Limit
I have below requirement, just wondering if there is a smart way to get this with minimal number of query :我有以下要求,只是想知道是否有一种聪明的方法可以用最少的查询来获得它:
Below is my two table User and Score, I want to segregate users into 4 groups based on their salary and average score.下面是我的两个表 User 和 Score,我想根据他们的薪水和平均分数将用户分为 4 组。 I should be able to query data with limit.我应该能够限制查询数据。 For example I could have millions of user so that I would like to query only top 10 for each group order by salary.例如,我可能有数百万用户,因此我只想按工资查询每个组订单的前 10 名。
Users with salary > Median of Salary (Based on below data it is 400) and average score > Median of Score(This is Constant: 5).薪水 > 薪水中位数(根据以下数据为 400)和平均分数 > 分数中位数(这是常数:5)的用户。 [6. Rocky, 8.Vicky]
[6. Rocky, 8.Vicky]
User with salary > Median of Salary (Based on below data it is 400) and average score < Median of Score(This is Constant: 5) [5.Roy, 7.Antony]
User with salary =< Median of Salary (Based on below data it is 400) and average score >= Median of Score(This is Constant: 5) [1.Jack, 2.Tony, 4.Bony]
User with salary =< Median of Salary (Based on below data it is 400) and average score <= Median of Score(This is Constant: 5) [3.Sham]
[6. Rocky, 8.Vicky]
薪水 > 薪水中位数(根据以下数据为 400)和平均分数 < 分数中位数(这是常数:5)的用户[5.Roy, 7.Antony]
薪水 =< 的用户薪水中位数(根据以下数据为 400)和平均分 >= 分数中位数(这是常数:5) [1.Jack, 2.Tony, 4.Bony]
薪水 =< 薪水中位数(基于在下面的数据上它是 400)和平均分数 <= 分数中位数(这是常数:5) [3.Sham]
Name user_id salary
Jack 1 100
Tony 2 200
Sham 3 300
Bony 4 400
Roy 5 500
Rocky 6 600
Antony 7 700
Vicky 8 800
id score user_id
1 4 1
2 8 1
3 9 1
4 2 2
5 10 2
6 3 3
7 6 4
8 7 4
9 2 5
10 4 5
11 9 6
12 1 7
13 5 8
14 9 8
15 2 8
16 10 8
This is a tweak on the answer in your previous question:这是对您上一个问题的答案的调整:
select u.*
from (select p.user_id, p.salary, avg(s.score) as avg_score,
row_number() over (partition by p.salary <= p.median_salary, avg(s.score) <= s.median_score order by rand()) as seqnum
from (select u.*,
percentile_cont(0.5) within group (order by salary) over () as median_salary
from users u
) u join
(select s.*,
percentile_cont(0.5) within group (order by score) over () as median_score
from score s
) s
on p.user_id = s.user_id
group by p.user_id, p.salary, p.median_salary
) u
where seqnum <= 10;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.