簡體   English   中英

如何使用SQL查詢不同的數據組

[英]How to query different group of data with SQL

我有以下要求,只是想知道是否有一種聰明的方法可以用最少的查詢來獲得它:

下面是我的兩個表 User 和 Score,我想根據他們的薪水和平均分數將用戶分為 4 組。

  1. 薪水 > 薪水中位數(根據以下數據為 400)和平均分數 > 分數中位數(這是常數:5)的用戶。 [6. Rocky, 8.Vicky]
  2. 薪水 > 薪水中位數(根據以下數據為 400)和平均分數 < 分數中位數(這是常數:5) [5.Roy, 7.Antony]
  3. 薪水 =< 薪水中位數(根據以下數據為 400)且平均分數 >= 分數中位數(這是常數:5) [1.Jack, 2.Tony, 4.Bony]
  4. 薪水 =< 薪水中位數(根據以下數據為 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 p.user_id, p.salary, avg(s.score) as avg_score,
       (case when p.salary <= p.median_salary and
                  avg(s.score) <= s.median_score
             then 'low-low'
             when p.salary <= p.median_salary and
                  avg(s.score) > s.median_score
             then 'low-high'
             when p.salary > p.median_salary and
                  avg(s.score) <= s.median_score
             then 'high-low'
             when p.salary > p.median_salary and
                  avg(s.score) <= s.median_score
             then 'high-high'
        end) as grouping             
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM