[英]how to get start_date and end_date from creation_time
需要帮助,我需要根据 is_active state 从 creation_time 获取 start_date 和 end_date。 我尝试了几个查询,但没有得到正确的结果。
表格示例
ID | 用户身份 | 姓名 | 领导者姓名 | 活跃 | 创建时间 |
---|---|---|---|---|---|
6 | 29 | 东风 | 作为 | 0 | 2021-10-10 |
620 | 29 | 东风 | RB | 0 | 2022-02-09 |
1088 | 29 | 东风 | 作为 | 1 | 2022-06-30 |
结果应该是这样的:
ID | 用户身份 | 姓名 | 领导者姓名 | 活跃 | 开始日期 | 结束日期 | 创建时间 |
---|---|---|---|---|---|---|---|
6 | 29 | 东风 | 作为 | 0 | 2021-10-10 | 2022-02-09 | 2021-10-10 |
620 | 29 | 东风 | RB | 0 | 2022-02-09 | 2022-06-30 | 2022-02-09 |
1088 | 29 | 东风 | 作为 | 1 | 2022-06-30 | 当前的日期() | 2022-06-30 |
请各位朋友帮忙,先谢谢了
根据问题部分和评论部分的信息,我相信 is_active=1 的行具有组的最新创建时间(基于 user_id)。这是在工作台中编写和测试的查询。
select id,user_id,name,leader_name,is_active,
t1.creation_time as start_date, case is_active when 0 then t2.creation_time else current_date() end as end_date,t1.creation_time
from (select id,user_id,name,leader_name,is_active,creation_time,@row_id:=@row_id+1 as row_id
from test,(select @row_id:=0)t
where user_id=29
order by creation_time
)t1
left join
(select creation_time,@row_num:=@row_num+1 as row_num
from test,(select @row_num:=0)t
where user_id=29
order by creation_time
)t2
on t1.row_id+1=t2.row_num
;
-- result set:
# id, user_id, name, leader_name, is_active, start_date, end_date, creation_time
6, 29, DF, AS, 0, 2021-10-10, 2022-02-09, 2021-10-10
620, 29, DF, RB, 0, 2022-02-09, 2022-06-30, 2022-02-09
1088, 29, DF, AS, 1, 2022-06-30, 2022-08-31, 2022-06-30
这还不是结束。 以防万一您想根据每个 user_id 组显示 output,下面是代码:
-- first of all insert the following 4 lines on top of the original table data, which has the same user_id 50
61 50 DF AS 0 2021-10-10
630 50 DF RB 0 2022-02-09
1188 50 DF TS 0 2022-06-30
2288 50 DF AS 1 2022-07-30
select id,t1.user_id,name,leader_name,is_active,
t1.creation_time as start_date, case is_active when 0 then t2.creation_time else current_date() end as end_date,t1.creation_time
from
(select id,user_id,name,leader_name,is_active,creation_time,@row_id:=@row_id+1 as row_id
from test,(select @row_id:=0)t
order by user_id,creation_time
)t1
left join
(select user_id,creation_time,@row_num:=@row_num+1 as row_num
from test,(select @row_num:=0)t
order by user_id,creation_time
)t2
on t1.user_id=t2.user_id and t1.row_id+1=t2.row_num
;
-- result set:
# id, user_id, name, leader_name, is_active, start_date, end_date, creation_time
6, 29, DF, AS, 0, 2021-10-10, 2022-02-09, 2021-10-10
620, 29, DF, RB, 0, 2022-02-09, 2022-06-30, 2022-02-09
1088, 29, DF, AS, 1, 2022-06-30, 2022-08-31, 2022-06-30
61, 50, DF, AS, 0, 2021-10-10, 2022-02-09, 2021-10-10
630, 50, DF, RB, 0, 2022-02-09, 2022-06-30, 2022-02-09
1188, 50, DF, TS, 0, 2022-06-30, 2022-07-30, 2022-06-30
2288, 50, DF, AS, 1, 2022-07-30, 2022-08-31, 2022-07-30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.