SQL Server 是否获取福尔斯在每个月末的日期列表?

xiozqbni  于 2022-12-22  发布在  其他
关注(0)|答案(3)|浏览(140)

我需要使用表1和表2获取从当前日期起过去3年的每个月末(不包括法定假日和周末)。表1包含2025-2017年的所有日期。表2包含2025-2017年的所有法定假日。
如何创建SQL脚本来达到这个结果?任何建议都可能会有帮助。预期结果将是日期的最后3年的endofmonth不包括法定假日和周末的列表。
表1有2列,DateId和FullDate列

DateID Fulldate

 1010392 2019-12-1
 1010393 2019-12-2
 1010394 2019-12-3
 1010395 2019-12-4
 .
 .
 101086 2019-12-31

表2有2列,DateId和Statutory_Holidays

Date ID   Stat_Holidays
 101085     2019-12-25
 101086     2019-12-26

返回的结果应该如下所示

WeekDay_FullDate_Past3yrs
2019-12-31
2020-1-31
2020-2-28
2020-3-31

已尝试以下操作:

select * from
 ( select a.Date from Table1 a where a.Date <= 
  '20221215' and a.Date >= DATEADD (YEAR, -3, getdate()) ) as t1
 join
 ( select EOMONTH(a.Date) as Date from Table1 a where a.Date <= '20221215' and a.Date >= DATEADD (YEAR, -3, getdate()) ) as t2 on t1.Date = t2.Date

我尝试了下面链接的解决方案,它没有解决我的问题。我希望获得过去3年每月最后一个工作日(不包括周末和假期)的列表
SQL Server - Get Last Business Data excluding holidays and Weekends

sczxawaw

sczxawaw1#

您可以按月份和年份分组,并采用最大日期(不包括节假日和周末):

SET DATEFIRST 1;
DECLARE @CurrentDate DATE = '20221215';

WITH cte
AS
(
    SELECT MAX(Date ) as EOMDate
    FROM Table1 
    WHERE DATEPART(weekday,Date) NOT IN (6,7)
    AND Date NOT IN (SELECT Date FROM Table2)
    GROUP BY YEAR(Date),MONTH(Date)
)
SELECT *
FROM cte
WHERE cte.EOMDate BETWEEN DATEADD(YEAR,-3,@CurrentDate) AND @CurrentDate;
deikduxw

deikduxw2#

这样就可以在主表中给予出每个月的最后一个工作日,只需按所需的时间段进行过滤即可:

SELECT TOP 1 WITH TIES FullDate
FROM Table1
WHERE FullDate NOT IN (SELECT Stat_Holidays FROM Table2) -- not holiday
    AND DATEPART(weekday, FullDate) NOT IN (7, 1) -- not saturday and sunday
ORDER BY DENSE_RANK() OVER(PARTITION BY YEAR(FullDate), MONTH(FullDate) ORDER BY FullDate DESC)
wlzqhblo

wlzqhblo3#

请检查表名和列名。

select  year(dates) _Year ,month(dates) _Month,EOMONTH(dates) endofMOnth from tabledate1 where DATENAME(DW, dates) not in ('Saturday','Sunday') 
and EOMONTH(dates)  not in (select holidaydate from tableholidays)
Group by year(dates),month(dates),EOMONTH(dates) 
order by year(dates) ,month(dates)

相关问题