[英]PostgreSQL partition by and select first row with specific column value
I have data in the following format:我有以下格式的数据:
ID DATE METRIC
1 1/1/19 1
1 1/3/19 1
1 1/5/19 0
2 1/2/19 0
2 1/9/19 0
2 1/11/19 0
3 1/1/19 0
3 1/2/19 0
3 1/3/19 1
What I am trying to accomplish is only take one row per ID and if there is a 1 metric take the first date with a 1. If there is not a 1 metric take the row and NULL the date.我想要完成的是每个 ID 只取一行,如果有 1 个指标,则第一个日期为 1。如果没有 1 个指标,则取该行并将日期设为 NULL。 My desired output would look like this:我想要的输出看起来像这样:
ID DATE METRIC
1 1/1/19 1
2 NULL 0
3 1/3/19 1
The closest I have come is doing a row_number() OVER (PARTITION BY ID order by DATE) as RN
however that just leaves me with numbered rows per ID.我最接近的是做一个row_number() OVER (PARTITION BY ID order by DATE) as RN
但这只会给我留下每个 ID 的编号行。 Is it possible to do a case when within a partition by?在分区内时是否可以做一个案例?
You can use DISTINCT ON
and conditional logic:您可以使用DISTINCT ON
和条件逻辑:
select distinct on(t.id)
t.id,
case when t.metric = 1 then t.date end date,
metric
from mytable t
order by t.id, t.metric desc, t.date
Demo on DB Fiddle : DB Fiddle 演示:
id | date | metric -: | :--------- | -----: 1 | 2019-01-01 | 1 2 | null | 0 3 | 2019-03-01 | 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.