【发布时间】:2016-10-01 18:09:03
【问题描述】:
鉴于以下table_a:
id | status | reg_date | so_date
----+------------------------------
1 | abc | 15-11-01 | 15-11-02
1 | def | 15-11-01 | 15-11-04
1 | abc | 15-11-01 | 15-11-06
2 | abc | 15-11-01 | 15-11-03
2 | abc | 15-11-01 | 15-11-04
2 | abc | 15-11-01 | 15-11-06
2 | abc | 15-11-01 | 15-11-08
3 | xyz | 15-11-01 | 15-11-03
3 | def | 15-11-01 | 15-11-08
3 | def | 15-11-01 | 15-11-09
以下是必需的:
对于每组id,如果status 是“abc”,则so_date 和reg_date 之间的最小差异。这会产生下表:
id | min_date
----+----------
1 | 1
2 | 2
3 | Null
下面的代码就足够了:
select
id,
distinct datediff('day', reg_date, min(so_date) over (partition by id)) as min_date
from table_a
where status ilike '%abc%'
但是,由于其他“选择”的限制,在基表中使用过滤器where status ilike '%abc%' 是不可行的。我尝试使用
select
id,
case when status is like '%abc%' then (distinct datediff('day', reg_date, min(so_date) over (partition by id))) end as min_date
from table_a
但这不起作用。任何见解/建议将不胜感激。谢谢
【问题讨论】:
标签: sql case partitioning where-in