在一条记录sql中将两个记录重组

时间:2019-07-18 11:15:11

标签: sql

我有特定雇员的以下记录:

  ID_Emp|Name    |Date          |TimeIn                   |TimeOut|InOrOut
   -----------------------------------------------------------------------
    11  |Jonh    |17/07/2019    |2019-07-17 07:19:36.00   |       |0
    11  |Jonh    |17/07/2019    |2019-07-17 17:19:36.00   |1      |
    11  |Jonh    |17/07/2019    |2019-07-17 08:12:36.00   |1      |
    11  |Jonh    |17/07/2019    |2019-07-17 08:30:36.00   |       |0
    11  |Jonh    |17/07/2019    |2019-07-17 17:19:36.00   |1      |
    11  |Jonh    |18/07/2019    |2019-07-18 07:32:36.00   |       |0
    11  |Jonh    |18/07/2019    2019-07-17 17:19:36.00    |1      |

InOrOut代表员工是否已签入或签出。

0 = IN 
1 = OUT

我想将记录检索为:

Jonh | 2019-07-17 07:19:36.00 | 2019-07-17 17:19:36.00 

如何在sql查询中实现这一目标?

2 个答案:

答案 0 :(得分:1)

假设给定逻辑日期的签入和签出总是在同一日期进行,那么简单的聚合查询就足够了:

SELECT
    Name,
    ID_Emp,
    Date,
    MAX(CASE WHEN InOrOut = 0 THEN TimeColumn END) AS TimeIn,
    MAX(CASE WHEN InOrOut = 1 THEN TimeColumn END) AS TimeOut
FROM yourTable
GROUP BY
    Name,
    ID_Emp,
    Date;

我假设只有一个时间戳列TimeColumn,并且您在示例数据中错误地发布了两个。

答案 1 :(得分:1)

假设行已正确交织-没有相邻的输入/输出,则可以使用lead()

select id_emp, name, date, timecol as timein, next_timecol as timeout       
from (select t.*,
             lead(timeOut) over (partition by id_emp order by timecol) as next_timeout
      from t
     ) t
where inorout = 0;

如果您想每天最早进/出时间,请使用聚合:

select id_emp, name, date,
       min(case when inorout = 0 then timecol end) as timein,
       max(case when inorout = 1 then timecol end) as timeout
from t
group by id_emp, name, date