Sql 如何根据Resdhift中的条件获取最短日期?

Sql 如何根据Resdhift中的条件获取最短日期?,sql,group-by,boolean,amazon-redshift,Sql,Group By,Boolean,Amazon Redshift,假设您拥有以下数据集: 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    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一行。我想要分组的方式是:如果布尔列为true,我想取最小值或最大值,如果可能的话,我想测试id的两个日期。如果id的所有布尔列都为false,那么我想取最高日期。所需的输出如下:

id    date_col       boolean_col
1     2020-01-05     1
2     2020-05-01     0
3     2020-03-05     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;
另一种方法将其视为优先级排序,并使用
联合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;
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;