Create a fiscal calendar in T-SQL(在 T-SQL 中创建会计日历)
问题描述
我正在尝试创建一个会计日历,其中会计年度从 7 月 1 日开始,一周被定义为周一至周日.
I am trying to create a fiscal calendar in which the fiscal year starts July 1 and a week is defined as Monday to Sunday.
但是例如;如果一个月中一周的第一天是星期六,那么星期六到星期日将被视为该月的第 1 周,新的一周从星期一开始,到星期日结束,依此类推.
But for example; if the 1st day in a week in a month is a Saturday, then Saturday to Sunday will be seen as 1 week in that month and the new week starts on Monday and ends on Sunday and so on.
请参阅下面我要创建的表格示例:
See sample of the table I want to create below:
- 期间是指会计年度的月份.
- Week 是该月的周数.
- 开始日期(周开始日期)是一周开始的那一天
- 结束日期(周结束日期)是一周结束的那一天.
- 星期几是开始日期和结束日期之间的日期.
- 年份
我想我需要一个程序,它可能需要会计年度的第一天,然后遍历一年中的所有日子,添加列开始和结束日期、周数、期间和日期所属的年份.
I am thinking that I need a procedure that maybe takes the first day of the fiscal year then iterates through all the days of the year adding the columns start and end date, week number, period and year the day belongs to.
推荐答案
另一种选择.这将生成 50 年是 0.703 秒
Yet another option. This will generate 50 years is 0.703 seconds
示例
Set DateFirst 1
Declare @Date1 date = '2017-07-01'
Declare @Date2 date = '2019-06-30'
Select Period = Dense_Rank() over (Partition By FY Order By FM)
,Week = Dense_Rank() over (Partition By FY,FM Order By FW)
,StartDate = Min(D) over (Partition By FY,FM,FW )
,EndDate = Max(D) over (Partition By FY,FM,FW )
,DayOfWeek = D
,Year = FY
From (
Select FY = DatePart(Year,@Date1)-1+sum(case when convert(varchar(5),@Date1,101)=convert(varchar(5),D,101) then 1 else 0 end) over (Order By D)
,FM = sum(case when DatePart(Day,D)=DatePart(Day,@Date1) then 1 else 0 end) over (Order By D)
,FW = sum(case when DatePart(WeekDay,D)=1 then 1 else 0 end) over (Order By D)
,D
From (
Select Top (DateDiff(DAY,@Date1,@Date2)+1)
D = DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),@Date1)
From master..spt_values n1,master..spt_values n2
) A1
) A
Order By D
这篇关于在 T-SQL 中创建会计日历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 T-SQL 中创建会计日历
基础教程推荐
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
