使用时间和服务日数据计算卡车的服务日期

Calculate service date of a truck with time and service day data

我们有一些卡车在不同的日子服务于一些目的地。在 Sql 服务器 table 中, table 如下所示。

TruckCode ServiceHour Monday Tuesday Wednesday Thursday Friday Saturday      
Route1    17:00       1       0      1         0        1       0
Route2    09:30       1       1      1         1        1       1
Route3    14:30       0       1      0         1        0       0

对此的解释 table, Route1 卡车在周一、周三、周五提供服务,服务时间为17:00。 Route2 货车每天都有服务,服务时间为09:30。 Route3 卡车在星期二、星期四提供服务,服务时间为14:30。

我有订单日期,这些订单有卡车代码和订单时间。我想计算订单送达的日期和时间。周日没有服务。

例如,下单时间为17:05,下单日为周一,货车代码为Route1的订单,将在周三17:00送达。因为,星期二不是Route1的服务日,星期一过了5分钟。

我正在研究基于 charindex 的解决方案,如下所示。

我将日期数据加入一个字符串,例如 Route1,10101001010100 ,这表示,第一个字符是 1 那么这条路线在星期一服务,第二个字符是 0 那么这条路线不服务星期二等

我用 ((datepart(dw,@orderInsertDate) + @@DATEFIRST-2) % 7+1)

得到了日期

而charindex函数是:

CHARINDEX('1','10101001010100',((datepart(dw,@orderInsertDate) + @@DATEFIRST-2) % 7+1)+
(case when ServeTime < getdate() then 1 else 0 end)
)

我也需要比较时间,因为例如周一 16:30 插入的 Route1 订单是同一天服务,但周一 17:30 插入的订单星期一服务于下星期三。仍然无法计算出正确的值,但我认为 charindex 会解决它。

如何计算?

从现在开始感谢。

这需要标准化数据,但我认为它可行。相信我,值得对数据进行规范化。

它不会换行到下周,但您可以检查是否为空并换行到第一次交货。

declare @R table (id int identity primary key, name varchar(20), tm time not null);
insert into @R (name, tm) values ('Route1', '17:00');
declare @D table (fk int, d tinyint not null);
insert into @D (fk, d) values (1, 2), (1, 4), (1, 6);

declare @dd int = 2;
declare @tt time = cast('17:05' as time);
select top (1) 
       r.name, r.tm, d.d, @dd as dOr, @tt as tOr 
from @R r 
join @D d
  on d.fk = r.id 
where r.id = 1 
  and  d.d > @dd 
   or (d.d = @dd and r.tm >= @tt)
order by d.d;

name                 tm               d    dOr         tOr
-------------------- ---------------- ---- ----------- ----------------
Route1               17:00:00.0000000 4    2           17:05:00.0000000