[英]Nth Business Day of next year
I have one table name as Table_A, which contain Business Day column and Date column. 我有一个表名称为Table_A,其中包含工作日列和日期列。
BD | Date
----|--------
3 | Aug-03-2017
15 | Aug-21-2017
7 | Sep-11-2017
20 | Oct-20-2017
14 | Nov-20-2017
What I want is, next year date with of same date month according to their corresponding BD 我想要的是,根据其相应的BD,明年日期与同一日期的月份相同
Desired Output: 所需输出:
BD | Date | Nxt_yr_Date
----|--------------|------------
3 | Aug-03-2017 | Aug-03-2018
15 | Aug-21-2017 | Aug-21-2018
7 | Sep-11-2017 | Sep-11-2018
20 | Oct-20-2017 | Oct-22-2018
14 | Nov-20-2017 | Nov-20-2018
18 | Dec-27-2017 | Dec-26-2018
Right now I have written a code, which convert "Date" to next year date then check if it is Saturday then add 2 days, if it is Sunday then add 1 day 现在,我已经编写了一个代码,将“日期”转换为明年的日期,然后检查是否是星期六,然后加上2天,如果是星期天,然后加上1天
My till now code: 我到目前为止的代码:
select
case
when datepart(dw,dateadd(year,1,(dateadd(day,1,[Date])))) = 1
then dateadd(year,1,(dateadd(day,2,[Date])))
when datepart(dw,dateadd(year,1,(dateadd(day,1,[Date])))) = 7
then dateadd(year,1,(dateadd(day,3,[Date])))
else dateadd(year,1,[Date])
end as Nxt_yr_Date
from Table_A
but not able make it for BD specific. 但无法实现BD专用。 Thanks in advance. 提前致谢。
If I understand you correctly, you want to find: 如果我对您的理解正确,则希望找到:
Here's one way to do it: 这是一种实现方法:
SET DATEFIRST 7
;WITH
Calendar(Date) AS
(
SELECT CONVERT(date, '2018-01-01')
UNION ALL
SELECT DATEADD(DAY, 1, Date)
FROM Calendar
WHERE Date < '2018-12-31'
),
BusinessCalendar(Date, BD) AS
(
SELECT Date
, ROW_NUMBER() OVER (PARTITION BY MONTH(Date) ORDER BY Date)
FROM Calendar
WHERE DATEPART(WEEKDAY, Date) NOT IN (1, 7)
)
SELECT A.BD
, A.Date
, CAL.Date AS NextYearDate
FROM #TableA A
INNER JOIN BusinessCalendar CAL ON MONTH(A.Date) = MONTH(CAL.Date)
AND A.BD = CAL.BD
OPTION (MAXRECURSION 0)
It uses 2 CTEs to handle the work: 它使用2个CTE来处理工作:
Calendar
is a recursive CTE that contains every day in 2018 Calendar
是递归CTE,包含2018年的每一天 BusinessCalendar
filters calendar to only leave out Monday to Friday, then number those days within each month BusinessCalendar
过滤日历以仅保留星期一至星期五,然后对每个月中的那些天进行编号 All that left is joining against your Table_A
. 剩下的就是加入到您的Table_A
。
(Note that this doesn't take into account any public holidays, just weekdays and weekends) (请注意,这没有考虑到任何公共假期,只是工作日和周末)
Does this do what you want? 这是您想要的吗?
select bid,
max(case when year(date) = 2017 then date end) as date_2017,
max(case when year(date) = 2018 then date end) as date_2018
from table_A
group by bid;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.