【问题标题】:How to query different group of data with SQL如何使用 SQL 查询不同的数据组
【发布时间】:2020-01-03 03:26:21
【问题描述】:

我有以下要求,只是想知道是否有一种聪明的方法可以用最少的查询来获得它:

下面是我的两个表用户和分数,我想根据他们的薪水和平均分数将用户分成 4 组。

  1. 工资 > 工资中位数(根据以下数据为 400)和平均得分 > 得分中位数(这是常数:5)的用户。 [6. Rocky, 8.Vicky]
  2. 有薪水的用户 > 薪水的中位数(根据下面的数据是 400)和平均分数 [5.Roy, 7.Antony]
  3. 用户的薪水 == 得分中位数(这是常数:5)[1.Jack, 2.Tony, 4.Bony]
  4. 工资=[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

【问题讨论】:

    标签: sql postgresql performance


    【解决方案1】:

    您可以使用窗口函数来计算子查询中的中值。剩下的只是聚合和条件逻辑:

    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
    

    【讨论】:

    • 谢谢!!但我也想提取有限制的记录。例如,我有数千条记录,我想按工资为每个组订单提取前 10 条记录。
    • @SekharDutta 。 . .这不是你问的问题,这回答了你在这里问的问题。如果您有其他问题,请将其作为问题提出。
    • 请在以下链接查看我的新问题:stackoverflow.com/questions/59578100/…
    猜你喜欢
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 2018-10-06
    • 1970-01-01
    • 2023-03-09
    • 2016-08-24
    • 2012-04-29
    相关资源
    最近更新 更多