从Zone - To Zone数据中获取特定信息 - Sql server 2012

时间:2017-03-30 06:02:18

标签: sql sql-server sql-server-2008 sql-server-2012 sql-server-2008-r2

我有一个表名称entrystate我只想要那些离开X区域并输入(A,B,C,D,E)区域,O状态意味着左边和1意味着进入区域的车辆数据

  ZoneId  VehId      TimeFirst                     State
    X       1    2016-07-01 00:39:25                 0
    x       2    2016-07-01 00:50:25                 0
    x       1    2016-07-01 00:52:25                 0
    x       2    2016-07-01 00:53:25                 0
    A       1    2016-07-02 12:50:25                 1
    A       1    2016-07-02 14:50:25                 1
    A       1    2016-07-04 15:50:25                 1
    f       3    2016-07-03 14:50:25                 0
    A       3    2016-07-04 14:50:25                 1
    B       2    2016-07-02 00:50:25                 1

必填结果

  fromZone  Tozone VehId      FromTime                   ToTime        
    X        A       1    2016-07-01 00:52:25         2016-07-02 12:50:25       
    x        B       2    2016-07-01 00:53:25         2016-07-02 00:50:25       

1 个答案:

答案 0 :(得分:1)

试试这个..

declare @table table (ZoneId nvarchar(2),VehId int,TimeFirst datetime ,[state] int
)

 insert into @table
      select    'X',       1,'2016-07-01 00:39:25',                 0
union all select     'x',       2,'2016-07-01 00:50:25',                 0
union all select     'x',       1,'2016-07-01 00:52:25',                 0
union all select     'x',       2,'2016-07-01 00:53:25',                 0
union all select     'A',       1,'2016-07-02 12:50:25',                 1
union all select     'A',       1,'2016-07-02 14:50:25',                 1
union all select     'A',       1,'2016-07-04 15:50:25',                 1
union all select     'f',       3,'2016-07-03 14:50:25',                 0
union all select     'A',       3,'2016-07-04 14:50:25',                 1
union all select     'B',       2,'2016-07-02 00:50:25',                 1


    SELECT t1.ZoneId AS fromZone
    ,t1.vehId
    ,t2.ZoneId AS ToZone
    ,max(t1.TimeFirst) AS FromTime
    ,min(t2.TimeFirst) AS ToTime
FROM @table t1
INNER JOIN @table t2 ON t1.VehId = t2.VehId
WHERE t1.ZoneId = 'X'
    AND t2.ZoneId IN ('A', 'B', 'f')
GROUP BY t1.ZoneId
    ,t1.vehId
    ,t2.ZoneId

<强>输出

fromZone     vehId  ToZone          FromTime                ToTime
    X           1       A   2016-07-01 00:52:25.000     2016-07-02 12:50:25.000
    x           2       B   2016-07-01 00:53:25.000     2016-07-02 00:50:25.000