【问题标题】:How can I get the minimum date based on a condition in Resdhift?如何根据 Redshift 中的条件获取最短日期?
【发布时间】:2021-03-10 05:43:56
【问题描述】:

假设您有以下数据集:

id    date_col       boolean_col
1     2020-01-01     0
1     2020-01-05     1
1     2020-02-01     0
1     2020-03-01     1
2     2020-01-01     0
2     2020-05-01     0
3     2020-01-01     0
3     2020-03-05     1

我的最终输出应该分组,每个 id 一行。我要分组的方式是:如果布尔列为真,我想带上最小值或最大值,如果可能的话,我想同时测试 id 的日期。如果 id 的所有布尔列都是假的,那么我想得到最高的日期。所需的输出将是这样的:

id    date_col       boolean_col
1     2020-01-05     1
2     2020-05-01     0
3     2020-03-05     1

关于如何获得这个的任何想法?我真的很难找到方法

【问题讨论】:

    标签: sql group-by boolean amazon-redshift


    【解决方案1】:

    一种方法是row_number():

    select t.*
    from (select t.*,
                 row_number() over (partition by id order by boolean_col desc, date desc) as seqnum
          from t
         ) t
    where seqnum = 1;
    

    还有另外两种有趣的方法。一种是巧妙地聚合:

    select id,
           coalesce(max(case when boolean_col = 1 then date end),
                    max(date)
                   ) as date,
           max(boolean_col)
    from t
    group by id;
    

    另一个将此视为优先级并使用union all

    select id, max(date), boolean_col
    from t
    where boolean_col = 1
    group by id
    union all
    select id, max(date), max(boolean_col)
    from t
    group by id
    having max(boolean_col) = 0;
    

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 1970-01-01
      • 2021-05-02
      • 2020-12-14
      • 2016-11-25
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多