我们正在使用 Mysql数据库,我们有 employee_transaction 的单个表。
employee_transaction 表
id | employee_id | date | transaction_type
------------------------------------------------------
1 | 1 | 2015-01-01 | 1
2 | 1 | 2015-07-01 | 1
3 | 1 | 2015-12-31 | 0
4 | 2 | 2014-02-01 | 1
5 | 1 | 2016-04-01 | 1
6 | 2 | 2014-11-30 | 0
7 | 1 | 2016-08-01 | 1
8 | 1 | 2016-10-31 | 0
等等。
要获得正确的结果,需要满足以下条件: -
两个连续的transaction_type的结果如下 结果是一个员工
我们需要 employee_transaction 表中以下输出的查询。
employee_id | start_date | end_date | transaction_type
------------------------------------------------------
1 | 2015-01-01 | 2015-06-30 | 1
1 | 2015-07-01 | 2015-12-31 | 1
1 | 2016-01-01 | 2016-03-31 | 0
1 | 2016-04-01 | 2016-07-31 | 1
1 | 2016-08-01 | 2016-10-31 | 1
1 | 2016-11-01 | (Null) | 0
2 | 2014-02-01 | 2014-11-30 | 1
提前致谢。
如果您有任何疑虑/需要澄清,请回复我。
答案 0 :(得分:1)
使用相关子查询获取每个employee_id的下一个日期,下一个transaction_type(按日期排序)。然后根据上述条件使用case
表达式。
select employee_id
,case when (transaction_type=0 and nxt_t_type=1) or (transaction_type=0 and nxt_t_type is null) then dt+interval '1' day
else dt
end as dt
,case when nxt_t_type=1 then nxt_dt-interval '1' day
when transaction_type=1 and nxt_t_type=0 then nxt_dt
when transaction_type=0 and nxt_t_type is null then null
end as nxt_dt
,transaction_type
from (select t1.*
,(select t2.dt from t t2 where t1.employee_id=t2.employee_id and t2.dt > t1.dt
order by t2.dt limit 1) as nxt_dt
,(select t2.transaction_type from t t2 where t1.employee_id=t2.employee_id and t2.dt > t1.dt
order by t2.dt limit 1) as nxt_t_type
from t t1
) x
答案 1 :(得分:0)
这是一个使用相关子查询加入每个员工的连续日期和状态信息的查询:
select
f.emp_id, f.trans_date, f.trans_type,
(select trans_date from emp_trans
where emp_id=f.emp_id and trans_date = (select min(trans_date)
from emp_trans where emp_id=f.emp_id
and trans_date > f.trans_date)
) as end_trans_date,
(select trans_type from emp_trans
where emp_id=f.emp_id and trans_date = (select min(trans_date)
from emp_trans where emp_id=f.emp_id
and trans_date > f.trans_date)
) as end_trans_type
from emp_trans as f;