SQL Query显示计时表

时间:2015-04-05 10:13:17

标签: sql sql-server tsql

我有一张这样的表

id   Marca  CodCartela  Line Post status Time
---- ------ ----------- ---- ---- ------ -----------------------
178  346    4516645709  AS01 55   1      2015-04-05 02:30:12.627
179  346    4516645709  AS01 55   0      2015-04-05 02:31:23.593
180  346    4516645709  AS01 88   1      2015-04-05 02:32:05.107
181  346    4516645709  AS01 88   0      2015-04-05 02:32:22.060

状态1表示IN,状态0表示OUT。 我想要的是在每条人的同一条线上显示进出时间。 实施例

id   Marca  CodCartela  Line Post status TimeIN                   TimeOUT
---- ---------------- ---- ---- ------ -----------------------------------------
178  346    4516645709  AS01 55   1      2015-04-05 02:30:12.627 2015-04-05 02:31:23.593

这是可能的还是我需要重新考虑所有的计时应用:(

4 个答案:

答案 0 :(得分:0)

简单使用conditional Aggregate

SELECT marca, 
       codcartela, 
       line, 
       post, 
       Max(CASE WHEN status = 1 THEN time END) AS TimeIN, 
       Max(CASE WHEN status = 0 THEN time END) AS TimeOUT 
FROM   yourtable 
GROUP  BY marca, 
          codcartela, 
          line, 
          post 

答案 1 :(得分:0)

我不知道具体的架构结构如何,并没有让你顺利,我不确定但是根据你的样本数据和所需的输出我认为你想要这样的东西:

select t1.marca, 
       t1.codcartela, 
       t1.line, 
       t1.post, 
       t1.time as TimeIN, 
       t2.time as TimeOUT 
FROM   table_name t1
LEFT OUTER JOIN   table_name t2 on t1.post=t2.post 
                     and t1.marca = t2.marca
WHERE t1.status=1 and isnull(t2.status,0)=0

编辑:将连接列更改为marca,如提及的那样

答案 2 :(得分:0)

假设组合post, status是唯一的,您可以进行加入:

select
   t1.*
  ,t2.Time as timeOut
from tab t1
left join tab t2
on t1.post = t2.post
and t2.status = 0
where t1.status = 1

否则您可能需要添加其他条件。

答案 3 :(得分:0)

这将跟踪每个人的进出。只需将CTE中的yourTable切换为实际的表名即可。

WITH CTE_yourTable
AS
(
    SELECT  *,
            ROW_NUMBER() OVER (PARTITION BY Marca ORDER BY [Time]) activity_num
    FROM yourTable
)

SELECT  A.ID,
        A.Marca,
        A.CodCartela,
        A.[Line],
        A.[Post],
        --A.[Status],
        A.[Time] AS TimeIn,
        B.[Time] AS [TimeOut]
FROM        CTE_yourTable A
LEFT JOIN   CTE_yourTable B
ON A.Marca = B.Marca
AND A.activity_num = B.activity_num - 1
WHERE   A.[Status] = 1

结果:

ID          Marca       CodCartela                              Line Post        TimeIn                 TimeOut
----------- ----------- --------------------------------------- ---- ----------- ---------------------- ----------------------
178         346         4516645709                              AS01 55          2015-04-0502:30:12.627 2015-04-0502:31:23.593
180         346         4516645709                              AS01 88          2015-04-0502:32:05.107 2015-04-0502:32:22.060