【问题标题】:Categorizing columns by percentiles from two tables in SQL在 SQL 中按百分比对两个表中的列进行分类
【发布时间】:2022-01-16 11:36:05
【问题描述】:

我有两个包含用户数据的表。

我需要创建 3 组用户,除以两个表中列的百分位数。

table_1:

user_no matches
3354 5
45744 30
21421 12
20121 50
21254 8
21454 2

table_2:

user_no level
3354 128
45744 37
21421 25
20121 11
21254 77
21454 3

我的目的是在最后展示user_no 和名为division 的新列,该列由两个表的平均百分位数确定。

提前谢谢你。

【问题讨论】:

    标签: sql percentile


    【解决方案1】:

    很可能是错误的,但这是一个开始。

    create table table_1 (
     user_no int primary key not null, 
     matches int not null
    );
    
    create table table_2 (
     user_no int primary key not null, 
     level int not null
    );
    
    insert into table_1 
    (user_no,     matches) values
      (3354,      5) 
    , (45744,     30) 
    , (21421,     12) 
    , (20121,     50) 
    , (21254,     8) 
    , (21454,     2);
    
    insert into table_2 
    (user_no,     level) values
      (3354,      128) 
    , (45744,     37) 
    , (21421,     25) 
    , (20121,     11) 
    , (21254,     77) 
    , (21454,     3);
    
    select user_no, matches, level
    , round((perc_matches+perc_level)/2, 2) as perc
    , ntile(3) over (order by (perc_matches+perc_level)/2 desc) division
    from
    (
        select *
        , round(100.0*matches/sum(matches) over(), 2) perc_matches
        , round(100.0*level/sum(level) over(), 2) perc_level
        from table_1
        join table_2 using(user_no)
    ) q
    
    用户号 |比赛 |水平 |聚碳酸酯 |分配 ------: | ------: | ----: | ----: | --------: 20121 | 50 | 11 | 25.32 | 1 第3354章5 | 128 | 25.11 | 1 45744 | 30 | 37 | 20.61 | 2 21254 | 8 | 77 | 17.44 | 2 21421 | 12 | 25 | 10.06 | 3 21454 | 2 | 3 | 1.47 | 3

    db小提琴here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 2022-11-29
      相关资源
      最近更新 更多