根据另一个表的活动天数计算日期

如何解决根据另一个表的活动天数计算日期

我想根据表值获得接下来的三天。表 1 包含邮政编码,表 2 包含带邮政编码的 orderid。假设如果我在 14-06-2021 收到邮政编码为 27520 的订单,那么预计交货日期将是星期三日期、星期五日期和星期一日期。日期将根据下表路线中的 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 
)

该表中的数据如下。 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 语句,如果数据以不同的格式开始,则不需要该语句,并且依赖于将服务器语言设置为英语 {{ 1}} 给出预期值);相反,这是一种与您一开始给我们提供的方法密切相关的方法。

说明

关于它是如何工作的:

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

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

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

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

  • 我们过滤 include 的日期以仅捕获我们交付的日期;那么接下来 3 周的日期列表会被过滤掉那些落在这些日子里的日期。我们按 n 排序(所以较早的日期在前)然后返回前 3 个日期;给我们接下来的 3 个交货日期作为我们的结果。


更新

要将 3 个结果返回为 3 个命名列而不是 3 个行,我们可以使用 PIVOT 语句。根据评论中的讨论,此版本使用您的原始表定义,其中 include = 1 和空白表示真值和假值。

true
,

我会分两步解决这个问题

  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),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,Sunday  
      FROM routes) p  
    UNPIVOT  
       (IsDeliveryDay FOR Day IN   
          (Monday,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

,

我会这样处理:

IHS %>%
  filter(Start.Date != "2020-11-13",Start.Date != "2021-01-08",Start.Date != "2021-01-15",Start.Date != "2021-05-07") %>% 
  filter(Template != "Campus Event - IHS Tour (VIRTUAL)") %>%
ggplot(aes(x = Start.Date)) +
  geom_line(aes(y = Registrants,color = "Registrants")) +
  geom_line(aes(y = Attendance,color = "Attendance")) +
  geom_line(aes(y = No.Show,color = "No.Show")) +
  theme_classic() +
  annotate("rect",xmin = as.Date("2020-11-20"),xmax = as.Date("2021-01-22"),ymin = 0,ymax = 14,alpha = .09) + 
  annotate("text",x = as.Date("2020-11-20"),y = 12,label = "No tours\nduring holiday",hjust = -1,vjust = 0.5,size = 3) +
  annotate("text",x = as.Date("2021-04-09"),y = 26,label = "26",hjust = .5,vjust = -.9,y = 15,label = "15",y = 11,label = "11",size = 3) +
  labs(x = "Date",y = "Count")+
  ggtitle("IHS Tour Registrants,Attendance,and No Show") +
  scale_x_continuous(limits = as.Date(c("2020-09-11","2021-04-30")),breaks = as.Date(c("2020-09-11","2020-09-18","2020-09-25","2020-10-02","2020-10-11","2020-10-16","2020-10-23","2020-10-30","2020-11-06","2020-11-20","2021-01-22","2021-01-29","2021-02-05","2021-02-12","2021-02-26","2021-03-05","2021-03-12","2021-03-19","2021-03-26","2021-04-09","2021-04-16","2021-04-23","2021-04-30","2021-04-30"))) +
  scale_color_manual(name = "Legend",values = c("#FF8000","#7A1F2E","#006699")) +
    scale_y_continuous(limits = c(0,27),breaks = c(0,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,26,27)) +
  theme(axis.title.y = element_text(angle = 0,vjust = .5)) +
    theme(legend.position = "top") +
  theme(axis.title.x = element_text(size=10,face = "bold"),axis.text.x  = element_text(size=10,angle = 90),axis.text.y = element_text(angle = 0,size = 9),axis.title.y = element_text(angle=0,size = 10,vjust = .5,face = "bold")) 

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

然后我用 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','0'),('27523','0'); declare @nextdays table(vdate date,dow int); INSERT INTO @nextdays (vdate) VALUES (DATEADD(dd,@test)),(DATEADD(dd,@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; 代替 UNION,因为它的要求数量有限,更容易理解。请注意,UNPIVOTUNION 限制为所需的 zip。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-