【问题标题】:Select min and max values while grouped by a third column按第三列分组时选择最小值和最大值
【发布时间】:2017-02-09 23:10:17
【问题描述】:

我有一个包含活动数据的表格,需要在按 client_id 和这些活动的时间分组时获取“spend_perc”最小值和最大值列表。

样本数据为:

camp_id  | client_id | start_date | end_date   |   spend_perc       
    7257 |    35224  | 2017-01-16 | 2017-02-11 | 100.05 
    7284 |    35224  | 2017-01-16 | 2017-02-11 | 101.08 
    7308 |    35224  | 2017-01-16 | 2017-02-11 |  101.3  
    7309 |    35224  | 2017-01-16 | 2017-02-11 |  5.8    
    6643 |    35224  | 2017-02-08 | 2017-02-24 |  79.38  
    6645 |    35224  | 2017-02-08 | 2017-02-24 |  6.84   
    6648 |    35224  | 2017-02-08 | 2017-02-24 |  100.01 
    6649 |    78554  | 2017-02-09 | 2017-02-27 |  2.5    
    6650 |    78554  | 2017-02-09 | 2017-02-27 |  18.5   
    6651 |    78554  | 2017-02-09 | 2017-02-27 |  98.5   

我想要得到的是每个 client_id 和同一活动时间(相同的开始/结束日期)内具有最小和最大“spend_perc”值的行:

camp_id  | client_id | start_date | end_date  |   spend_perc       
    7308 |    35224  | 2017-01-16 | 2017-02-11 |  101.3  
    7309 |    35224  | 2017-01-16 | 2017-02-11 |  5.8    
    6645 |    35224  | 2017-02-08 | 2017-02-24 |  6.84   
    6648 |    35224  | 2017-02-08 | 2017-02-24 |  100.01 
    6649 |    78554  | 2017-02-09 | 2017-02-27 |  2.5    
    6651 |    78554  | 2017-02-09 | 2017-02-27 |  98.5   

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    smth like:?

    with a as 
    (select distinct 
    camp_id,client_id,start_date,end_date,max(spend_perc) over (partition by start_date,end_date),min(spend_perc) over (partition by start_date,end_date)
    from tn
    )
    select camp_id,client_id,start_date,end_date,case when spend_perc=max then max when spend_perc = min then min end spend_perc
    from a
    order by camp_id,client_id,start_date,end_date,spend_perc
    

    【讨论】:

      【解决方案2】:

      我认为你会想要摆脱 camp_id 字段,因为在这种情况下这将毫无意义。所以你想要这样的东西:

       SELECT client_id, start_date, end_date, 
              min(spend_perc) as min_spend_perc, max(spend_perc) as max_spend_perc
         FROM mytable
        GROUP BY client_id, start_date, end_date;
      

      按您想要的标准分组,并选择 min 和 max 作为这些值的唯一组合(即每行)的列。

      【讨论】:

      • 谢谢 Chris,不过我确实需要结果中的 camp_id。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 2013-11-08
      • 2021-12-04
      • 2020-05-16
      • 2022-06-23
      相关资源
      最近更新 更多