【问题标题】:Get specific from Zone - To Zone data - Sql server 2012从区域获取特定 - 到区域数据 - Sql server 2012
【发布时间】:2017-03-30 06:02:17
【问题描述】:

我有一个表名入口状态,我只想要那些离开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       

【问题讨论】:

  • 请添加解决方案
  • @Anup 解甲酸盐添加
  • 您使用什么 SQL 版本?,因为 SQL Server 2016 具有从值切换区域的新功能。
  • @MarcGuillot Sql server 2012
  • @Doe,我的意思是在时区,但我重新阅读了你的帖子,我发现这不是你问的。对不起。

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


【解决方案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

【讨论】:

  • 还是同样的演示,我有 10 行
  • 亲爱的演示显示错误的输出,请查看所需的结果
  • 错误的数据我想要超过 7 个月的数据,不包括分组中的日期,你找不到确切的结果
猜你喜欢
  • 2012-02-14
  • 2019-04-04
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 2015-04-03
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多