Date id output
11/26/2018 12:24 A 1
12/10/2018 23:34 A 0
12/11/2018 16:03 A 0
12/11/2018 16:34 A 0
12/12/2018 9:58 A 0
12/13/2018 9:27 A 1
12/6/2018 8:48 B 1
12/26/2018 8:49 B 1
我正在尝试创建一个逻辑值为1或0的新列。
我正在尝试在SQL查询中实现逻辑,以使输出列基于逻辑为1或0。有人可以帮我吗?
答案 0 :(得分:0)
这应该可以处理您的条件:
select t.*,
( (seqnum = 1) or
(max_date > min_date + interval '15 day')
)::int as flag
from (select t.*,
row_number() over (partition by id order by date desc) as seqnum,
max(date) over (partition by id) as max_date,
min(date) over (partition by id) as min_date
from t
) t;
您的第二个条件与最后一个条件是多余的。如果计数为1,则该记录为最后一条记录。
答案 1 :(得分:0)
此查询应执行以下操作:
with
x as (
select
id,
min(date) as mind,
max(date) as maxd,
count(*) as cnt
from my_table
group by id
),
select
t.date,
t.id,
case
when t.date = x.maxd then 1
when datediff('day', x.mind, x.maxd) > 15 then 1
when x.cnt <= 1 then 1
else 0 end as output
from my_table t
join x on x.id = t.id