TSQL查找具有可变日期的会计月的第一天和最后一天

时间:2013-11-18 16:17:33

标签: sql date reporting-services

我公司的财务日历具有可变的开始和结束日期,例如,

Period 1 - 04-01-2013 to 04-26-2013
Period 2 - 04-27-2013 to 05-29-2013 
...

我的SQL Server 2008数据库中有一个日期维度,用于存储所有会计月和年。

很容易找出具有日历日期的MTD,YTD,但我似乎无法在财政日期找出相同的结果。

我正在尝试根据销售数据创建一些计算成员。

那么如何才能获得第2期的第一天。

1 个答案:

答案 0 :(得分:1)

假设您的日期表包含必填字段,您的查询可能类似于:

 select yourfields
 from yourtables
 join date on date.date = SomeOtherTable.date
 join (select min(date) mindate
 from date
 where fiscal_year = TheYearYouWant
 and fiscal_period = ThePeriodYouWant) temp on date.date = mindate

请注意,没有会计年度的期间号码也会为您提供上一会计年度的结果。您可以使用会计年度字段处理此操作,也可以通过为您的会计期间命名为“F2013 / 14 P1”。就个人而言,我更喜欢财政年度的单独领域。

编辑从此处开始

上面的查询仅为您提供一天的结果。如果你想要当前时期的结果,这样的事情就可以了。

 select yourfields
 from yourtables
 join date on date.date = SomeOtherTable.date
 join (select fiscal_year fy, fiscal_period fp
 from date
 where date = current_date) temp on date.fiscal_year = fy and date.fiscal_period = fp

请注意,不同的数据库有不同的方式返回当前日期,而您没有指定自己的日期。