根据另一个 table 活跃天数值计算日期

Calculate date base on another table active days values

我想根据 table 值获取接下来的三天。 Table 一个包含邮政编码,table 2 包含带邮政编码的 orderid。假设如果我在 14-06-2021 收到邮政编码为 27520 的订单,那么预计交货日期将是星期三、星期五和星期一。日期将根据以下 table 条路线中 Zip 可用的天数计算。

CREATE TABLE [dbo].[ROUTES ](
    [zip] [varchar](255) NULL,  
    [Monday] [varchar](255) NULL,
    [Tuesday] [varchar](255) NULL,
    [Wednesday] [varchar](255) NULL,
    [Thursday] [varchar](255) NULL,
    [Friday] [varchar](255) NULL,
    [Saturday] [varchar](255) NULL,
    [Sunday] [varchar](255) NULL,
    [id] [varchar](255) NULL 
)

这个table中的数据如下。 1 表示该路线的有效日期。

zip     Monday  Tuesday Wednesday Thursday Friday Saturday Sunday 
27520   1       0       1         0        1      0         0

预计 14-06-2021 的结果将低于

ExpectedDate1 = 16-06-2021
ExpectedDate2 = 18-06-2021
ExpectedDate3 = 21-06-2021

感谢您的帮助。

这是使用您当前设置的一种可能的解决方案...

SQL Fiddle Example

declare @orderDate datetime = '2021-06-14'
, @orderZipCode nvarchar(10) = '27520'

declare @start datetime = dateadd(day, 1, @orderDate)
       ,@end  datetime =  dateadd(day, 22, @orderDate)

select top 3 CAST(s.n as datetime)
from dbo.generate_series(cast(@start as bigint), cast(@end as bigint), default, default) s
where DateName(dw, CAST(s.n as datetime)) in (
    select dw
    from ( select * from ROUTES where zip = @orderZipCode ) r
    UNPIVOT (include for dw in (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)) upvt
    where upvt.include = 1
 )
 order by s.n

这使用生成系列函数 I describe here

create function dbo.generate_series
(
      @start bigint
    , @stop bigint
    , @step bigint = 1
    , @maxResults bigint = 0 --0 = unlimited
)
returns @results table(n bigint)
as
begin

    --avoid infinite loop (i.e. where we're stepping away from stop instead of towards it)
    if @step = 0 return
    if @start > @stop and @step > 0 return
    if @start < @stop and @step < 0 return
    
    --ensure we don't overshoot
    set @stop = @stop - @step

    --treat negatives as unlimited
    set @maxResults = case when @maxResults < 0 then 0 else @maxResults end

    --generate output
    ;with myCTE (n,i) as 
    (
        --start at the beginning
        select @start
        , 1
        union all
        --increment in steps
        select n + @step
        , i + 1
        from myCTE 
        --ensure we've not overshot (accounting for direction of step)
        where (@maxResults=0 or i<@maxResults)
        and 
        (
               (@step > 0 and n <= @stop)
            or (@step < 0 and n >= @stop)
        )  
    )
    insert @results
    select n 
    from myCTE
    option (maxrecursion 0) --sadly we can't use a variable for this; however checks above should mean that we have a finite number of recursions / @maxResults gives users the ability to manually limit this 

    --all good  
    return
    
end

注意:这不是最干净的方法(例如,这使用了 unpivot 语句,如果数据以不同的格式开始,则不需要该语句,并且依赖于将服务器语言设置为英语datename 给出期望值);相反,它是一种与您一开始给我们的方法紧密相关的方法。

说明

关于其工作原理:

  • @orderDate@orderZipCode 是保存输入数据的变量。在现实世界中,您可能会将此代码包装在一个函数中,这些将是您传递给它的参数。

  • @start@end 是根据您的订单日期的次日到您的订单日期的 3 周和次日的日期。这些是您可能有订单日期的日期列表的外部边界。我去了 3 周,因为如果只勾选 1 天(例如星期一),你每周就会有 1 次约会。如果勾选了更多的天数,则不需要这个完整的(例如,如果您总是勾选 3 天,则只需要 1 周)。如果没有勾选天数,无论我们花了多少周,您都不会得到任何结果。

  • generate_series 为我们提供了开始和结束之间(包括在内)的日期列表。有关其工作原理的信息,请参阅 this post

  • unpviot 将每个邮政编码的单行转换为 7 行,其中 dw 列采用源行的列名,include 标志基于源行的列值。

  • 我们过滤 include = 1 的日期,以仅捕获我们交付的那些日子;然后在接下来的 3 周内的日期列表中筛选出属于这些天的日期。我们按 n 排序(所以较早的日期排在第一位)然后 return 前 3 个日期;给我们接下来的 3 个交货日期作为结果。


更新

要return 将 3 个结果作为 3 个命名列而不是 3 行,我们可以使用 PIVOT 语句。根据评论中的讨论,此版本使用您最初的 table 定义,其中 true 和空白表示真值和假值。

declare @orderDate datetime = '2021-06-14'
, @orderZipCode nvarchar(10) = '27520'

declare @start datetime = dateadd(day, 1, @orderDate)
       ,@end  datetime =  dateadd(day, 22, @orderDate)

select ExpectedDate1, ExpectedDate2, ExpectedDate3
from (
  select top 3 'ExpectedDate' + cast(row_number() over (order by n) as nvarchar(12)) r
  , CAST(s.n as datetime) ExpectedDate 
  from dbo.generate_series(cast(@start as bigint), cast(@end as bigint), default, default) s
  where DateName(dw, CAST(s.n as datetime)) in (
      select dw
      from ( select * from ROUTES where zip = @orderZipCode ) r
      UNPIVOT (include for dw in (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)) upvt
      where upvt.include = 'true'
   )
   order by s.n
 ) x
 pivot (
   max (ExpectedDate)
   for r in (ExpectedDate1,ExpectedDate2,ExpectedDate3)
 ) pvt

我会分两步解决这个问题

  1. 使用 CTE 生成接下来 7 个日期的列表
  2. 逆透视有关交货天数的数据以获取行并将其加入上面的 1)

WITH next_7_days(dt, weekday) 
AS (
    SELECT 
        cast(GETDATE() as date), 
        DATENAME(DW,GetDate())
    UNION ALL
    SELECT    
        CAST(CAST(dt AS DATETIME)+1 AS DATE), 
        DATENAME(DW, CAST(dt AS DATETIME) + 1)
    FROM    
        next_7_days
    WHERE dt < DATEADD(day,6,GetDate())
), routes_upvt 
AS
(
    SELECT Zip, Day, IsDeliveryDay  
    FROM   
       (SELECT zip, Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday  
      FROM routes) p  
    UNPIVOT  
       (IsDeliveryDay FOR Day IN   
          (Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday )  
    )AS unpvt
)
SELECT nsd.dt 
FROM routes_upvt r
INNER JOIN next_7_days nsd
 ON r.Day = nsd.weekday
WHERE zip=27520
AND IsDeliveryDay=1

实例:https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=c5b4f08ef5bf53b6d1854b1f795344de&hide=8

我会这样处理:

declare @test date = '2021-06-14';
declare @zip varchar(7) = '27520';

declare @routes table (zip varchar(255), monday varchar(255), tuesday varchar(255), wednesday varchar(255), thursday varchar(255), friday varchar(255), saturday varchar(255), sunday varchar(255));

INSERT INTO @routes VALUES 
('27520', '1', '0', '1', '0', '1', '0', '0'),
('27523', '1', '1', '0', '1', '1', '0', '0');

declare @nextdays table(vdate date, dow int);

INSERT INTO @nextdays (vdate) VALUES
(DATEADD(dd, 1, @test)),
(DATEADD(dd, 2, @test)),
(DATEADD(dd, 3, @test)),
(DATEADD(dd, 4, @test)),
(DATEADD(dd, 5, @test)),
(DATEADD(dd, 6, @test)),
(DATEADD(dd, 7, @test)),
(DATEADD(dd, 8, @test)),
(DATEADD(dd, 9, @test)),
(DATEADD(dd, 10, @test)),
(DATEADD(dd, 11, @test)),
(DATEADD(dd, 12, @test)),
(DATEADD(dd, 13, @test)),
(DATEADD(dd, 14, @test)),
(DATEADD(dd, 15, @test)),
(DATEADD(dd, 16, @test)),
(DATEADD(dd, 17, @test)),
(DATEADD(dd, 18, @test)),
(DATEADD(dd, 19, @test)),
(DATEADD(dd, 20, @test)),
(DATEADD(dd, 21, @test));

UPDATE @nextdays SET dow = DATEPART(dw, vdate);


WITH cte AS
(SELECT 1 as dow, sunday from @routes WHERE zip = @zip
UNION 
SELECT 2 as dow, monday from @routes WHERE zip = @zip 
UNION 
SELECT 3 as dow, tuesday from @routes WHERE zip = @zip 
UNION 
SELECT 4 as dow, wednesday from @routes WHERE zip = @zip 
UNION 
SELECT 5 as dow, thursday from @routes WHERE zip = @zip 
UNION 
SELECT 6 as dow, friday from @routes WHERE zip = @zip 
UNION 
SELECT 7 as dow, saturday from @routes WHERE zip = @zip)
SELECT TOP 3 vdate
FROM @nextdays n
INNER JOIN cte c ON n.dow = c.dow AND c.sunday = '1'
ORDER BY n.vdate;

我在 table 变量中插入 21 个日期,以防给定的 zip 只有 1 个交货日期。显然,如果所有的拉链都有至少 2 或 3 个交货日,您可以减少插入的数量。

然后我做一个 UNION 而不是 UNPIVOT,只是因为在有限数量的需求下它更容易理解。请注意,UNIONSELECT 限制为所需的 zip。

有一点需要注意,在以这种方式进行UNION时,如果列名不同,则结果列的名称是第一个SELECT中的列的名称UNION。因此 JOIN 在 c.sunday = '1'.