获取创建时间的开始日期和结束日期
P粉265724930
P粉265724930 2024-02-21 18:25:26
0
1
386

需要帮助,我需要根据is_active状态从creation_time获取start_date和end_date。 我尝试了几次查询,但没有得到正确的结果。

表格示例

id user_id 姓名 leader_name is_active 创建时间
6 29 DF AS 0 2021-10-10
620 29 DF RB 0 2022-02-09
1088 29 DF AS 1 2022-06-30

结果应该如下所示:

id user_id 姓名 leader_name is_active 开始日期 结束日期 创建时间
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 CURRENT_DATE() 2022-06-30

请帮助我的朋友,先谢谢你们

P粉265724930
P粉265724930

全部回复(1)
P粉495955986

根据问题部分和评论部分中的信息,我相信 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 组显示输出,请使用以下代码:

-- 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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!