Sql-Server

如何查找自財月開始以來的天數?

  • August 27, 2014

這與我的問題有關如何在 SQL Server 中查找上個月的第 XX 天?

會計月從每個月的 26 日開始。

我需要從任何日期找出:

  • 會計月的開始日期 (Start_Of_Fiscal_Month)
  • 進入會計月的天數 (Day_Of_Fiscal_Month)

例如:

CurrentDate - '2014-04-26'

Start_Of_Fiscal_Month = 2014-04-26
Day_Of_Fiscal_Month = 1

CurrentDate - '2014-05-02'

Start_Of_Month = 2014-04-26
Day_Of_Fiscal_Month = 7

這將做到:

DECLARE @d DATE = '20140502', @dm TINYINT = 26;
DECLARE @Start_Of_Fiscal_Month DATE

SET @Start_Of_Fiscal_Month = DATEADD(DAY, @dm-1, DATEADD(MONTH, -1 + DATEPART(dd, @d)/26, DATEADD(DAY, 1-DAY(@d), @d)));
SELECT @Start_Of_Fiscal_Month
SELECT DATEDIFF(dd, @Start_Of_Fiscal_Month, @d) + 1

引用自:https://dba.stackexchange.com/questions/75087