SQL查询获取经过时间的百分比计算到下一行的总时间和时间

时间:2017-03-24 12:56:36

标签: sql sql-server

我有一个这样的MS SQL表(返回可变行数):

TimeStamp               State

2015-04-27 09:49:14.567 SETUP
2015-04-27 10:10:07.340 EXECUTING
2015-04-27 14:15:12.017 WAITING
2015-04-27 14:15:48.263 EXECUTING
2015-04-27 14:29:10.773 WAITING
2015-04-27 14:29:38.177 EXECUTING
2015-04-28 01:58:54.340 WAITING
2015-04-28 02:03:25.257 CLOSED

现在我需要一个查询来计算每个时间戳的百分比开始和结束(实际值只是符号):

TimeStamp               State         PercentageStart PercentageEnd

2015-04-27 09:49:14.567 SETUP         0               8
2015-04-27 10:10:07.340 EXECUTING     8               20
2015-04-27 14:15:12.017 WAITING       20              26
2015-04-27 14:15:48.263 EXECUTING     26              28
2015-04-27 14:29:10.773 WAITING       28              30
2015-04-27 14:29:38.177 EXECUTING     30              90
2015-04-28 01:58:54.340 WAITING       90              100
2015-04-28 02:03:25.257 CLOSED        100             NULL

因此,第一个和最后一个TimeStamp记录之间的时间是100%。 我想我需要一个指针或东西,但不确定:/

提前问候和感谢!

2 个答案:

答案 0 :(得分:2)

declare @t table ([TimeStamp] datetime, [State] varchar(32));
insert into @t values 
  ('2015-04-27T09:49:14.567','SETUP'),
  ('2015-04-27T10:10:07.340','EXECUTING'),
  ('2015-04-27T14:15:12.017','WAITING'),
  ('2015-04-27T14:15:48.263','EXECUTING'),
  ('2015-04-27T14:29:10.773','WAITING'),
  ('2015-04-27T14:29:38.177','EXECUTING'),
  ('2015-04-28T01:58:54.340','WAITING'),
  ('2015-04-28T02:03:25.257','CLOSED')

Select firstTS, startts, endts, duration,
   100 * Datediff(second, firstTS, startts) / duration startPcnt,
   100 * Datediff(second, firstTS, endts)  / duration  endPcnt
From (Select s.timestamp startts, s.state, e.timestamp endts,
    (Select Min(timestamp) from @t) firstTS,
    (Select cast(DateDiff(second, Min(timestamp), Max(timestamp)) as float) from @t) duration
From @t s join @t e
    on e.timestamp =
       (Select Min(timestamp) from @t
        where timestamp > s.timestamp))x

答案 1 :(得分:2)

这样的事情应该有效:

var pathToModelPar = ConfigFactory.load("myConfig.conf")
var pathToModel = pathToModelPar.getString("pathToModel")
var model = GradientBoostedTreesModel.load(sc,pathToModel)

val ex = new ScheduledThreadPoolExecutor(1)
val task = new Runnable {
    def run() = {
      pathToModelPar = ConfigFactory.load("myConfig.conf")
      pathToModel = pathToModelPar.getString("pathToModel")
      model = GradientBoostedTreesModel.load(sc,pathToModel)
    }
  }
val f = ex.scheduleAtFixedRate(task, 1, 1, TimeUnit.HOURS)

myDStream.foreachRDD(myRDD => {
  myRDD.foreachPartition({ partitionOfRecords =>
    //...
    val predictions = model.predict(...)
    //...
  })
})

Demo here