在日期基础记录返回

时间:2014-06-26 05:53:43

标签: sql-server sql-server-2008

我有这样的表结构

 vehid   TimeFirst      TimeLast       Inside

  1      26/06/2014     null              0        
  2      26/06/2014     26/06/2014        1 
  2      26/06/2014     null              0
  3      26/06/2014     26/06/2014        1

我想只返回那些基于veh进入并在同一天离开的记录,只选择那些车辆的左侧记录。内侧0表示车辆左侧,1表示输入。下方输出

    vehid   TimeFirst      TimeLast       Inside

     2      26/06/2014       null          0

4 个答案:

答案 0 :(得分:0)

试试这个

SELECT S.* FROM Table1 T JOIN Table1 S ON
       T.TimeFirst = T.TimeLast AND 
       T.Inside = 1 AND 
       T.TimeLast = S.TimeFirst
WHERE S.Inside = 0 AND S.Vehid = T.Vehid 

<强> FIDDLE DEMO

输出将是:


+---------+---------------+---------------+-------------+
| VEHID   | TIMEFIRST     | TIMELAST      | INSIDE      |
+---------+---------------+---------------+-------------+
| 2       | 2014-06-26    | (null)        | 0           |
+---------+---------------+---------------+-------------+

答案 1 :(得分:0)

在这里,您可能需要从日期时间中排除时间:

select * from tableName a
    where          
    convert(date, timeFirst) in ( select convert(date, timeLast) from tableName where id = a.id) 
    and inside = 0 

答案 2 :(得分:0)

尝试这样的事情:

SELECT Ent.VehID, Ent.TimeFirst, Exit.TimeLast, Exit.Inside
FROM myTable Ent
JOIN myTable Exit
ON Ent.TimeFirst = Exit.TimeFirst
AND Ent.VehID = Exit.VehID 
AND Ent.Inside = 1 AND Exit.Inside = 0

如果同一车辆同一天有多个出入口,您将获得重复记录,您需要使用Distinct

答案 3 :(得分:0)

您可以使用此

SELECT  P2.*
FROM    Parking P1 INNER JOIN
        Parking P2 ON P2.VehID = P1.VehID AND 
                      P2.TimeFirst = P1.TimeLast
WHERE   P1.Inside = 1 AND P2.Inside = 0