【发布时间】:2017-06-17 11:54:40
【问题描述】:
我们正在使用 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 始终为 1。
- 任何员工都不能有连续的 transaction_type=0。
-
两个连续的transaction_type的结果如下。这些 结果适用于一名员工
- 如果 Transaction_type=1。 那么 start_date=第一个交易日期,end_date=第二个交易日期-1,transaction_type=1。
- 如果第一个 Transaction_type=1 并且下一个 transaction_type=0。 那么 start_date=第一个交易日期,end_date=第二个交易日期 和 transaction_type=1。
- 如果第一个 Transaction_type=0 并且下一个 transaction_type=1。 那么 start_date=第一笔交易日期+1,end_date=第二笔交易 date-1 和 transaction_type=0。
- 如果在transaction_type=0之后没有找到交易。 那么 start_date=第一个交易日期+1,end_date=空和 transaction_type=0。
我们需要 employee_transaction 表的以下输出的Query。
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
提前致谢。
如果您有任何疑虑/需要澄清,请回复我。
【问题讨论】:
-
我删除了不兼容的数据库标签。请标记您真正使用的数据库。此外,使用您提供的数据
order by employee_id, start_date)有效。规则背后的原因有点不清楚。交易是什么意思? -
嗨@GordonLinoff,我已经更新了问题中的所有细节。感谢您的建议。