鉴于以下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
组,so_date
和reg_date
之间的最小差异,如果status
是" abc"。这产生了下表:
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
但是这没用。任何见解/建议将不胜感激。感谢
答案 0 :(得分:1)
根据你的样本应
select
id
, min (datediff( so_date, reg_date )) as min_date
from table_a
where status ='abc'
group by id
如果你不想要蝙蝠案件那么
select
case status when 'abc' then id end
, case status when 'abc' then min (datediff( so_date, reg_date )) end as min_date
from table_a
group by id