[英]How to query different group of data with SQL with Limit
我有以下要求,只是想知道是否有一種聰明的方法可以用最少的查詢來獲得它:
下面是我的兩個表 User 和 Score,我想根據他們的薪水和平均分數將用戶分為 4 組。 我應該能夠限制查詢數據。 例如,我可能有數百萬用戶,因此我只想按工資查詢每個組訂單的前 10 名。
薪水 > 薪水中位數(根據以下數據為 400)和平均分數 > 分數中位數(這是常數:5)的用戶。 [6. Rocky, 8.Vicky]
[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
這是對您上一個問題的答案的調整:
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.