从SQL Server中的日期范围中提取年,月和日的数量

时间:2014-04-28 12:00:50

标签: sql-server date-formatting

我正在寻找从日期范围中提取年,月和日的可能性。

示例:

From: 01/01/2012 To: 08/17/2014
Result: 2 years, 8 month and 17 days

我知道如何对此进行编码,但也许某人有一个天才的解决方案如何在SQL中使用内置命令执行此操作。或者已经取得了快速而良好的工作职能。

如果不是,我将需要编写一个sql内联函数代码,并在此处作为答案提交文档。

2 个答案:

答案 0 :(得分:0)

首先,我正在考虑改变围绕太阳的轨道的方法,以便将其修正为一年360天。但这可能会以一些不良副作用结束......

正如我想要的确切数量(见下文),它似乎按照我的需要工作。如果有人需要,我会分享这个讨论,改进和分享。

DECLARE @start datetime;
DECLARE @end datetime;
DECLARE @current datetime;
DECLARE @year int
DECLARE @month int
DECLARE @days int;
DECLARE @daytmp int;

-- note start date earliest: 1/1/1753
SET @start = CAST('28.02.1753' AS datetime)
SET @end = GETDATE() --CAST('31.12.2016' AS datetime)
SET @current = @start

SET @days = (SELECT DATEDIFF(day, @start, @end))
SET @year = 0;

WHILE @days>365
BEGIN
  SET @days = @days - (SELECT DATEDIFF(day, @current, DATEADD(YEAR, 1, @current)))
  SET @current = DATEADD(YEAR, 1, @current)
  SET @year = @year + 1
END

SET @month = 0;
SET @daytmp = @days

WHILE @daytmp>28
BEGIN
  SET @daytmp = @days - (SELECT DATEDIFF(day, @current, DATEADD(MONTH, 1, @current)))
  IF (@daytmp>0) BEGIN
    SET @days = @daytmp
    SET @current = DATEADD(MONTH, 1, @current)
    SET @month = @month + 1
  END
END

PRINT @year
PRINT @month
PRINT @days

我把它移到了table函数中,它返回位置1,2,3的3个值,所以我可以在select语句中使用它。

CREATE FUNCTION dbo.sf_GetYearMonthDayFromRange(@start datetime, @end datetime)
RETURNS @result TABLE ([value] int, [position] int)
AS
BEGIN
  DECLARE @current datetime;
  DECLARE @year int
  DECLARE @month int
  DECLARE @days int;
  DECLARE @daytmp int;

  SET @current = @start
  SET @days = (SELECT DATEDIFF(day, @start, @end))
  SET @year = 0;

  WHILE @days>365
  BEGIN
    SET @days = @days - (SELECT DATEDIFF(day, @current, DATEADD(YEAR, 1, @current)))
    SET @current = DATEADD(YEAR, 1, @current)
    SET @year = @year + 1
  END

  SET @month = 0;
  SET @daytmp = @days

  WHILE @daytmp>28
  BEGIN
    SET @daytmp = @days - (SELECT DATEDIFF(day, @current, DATEADD(MONTH, 1, @current)))
    IF (@daytmp>0) BEGIN
      SET @days = @daytmp
      SET @current = DATEADD(MONTH, 1, @current)
      SET @month = @month + 1
    END
  END

  INSERT INTO @result SELECT @year,  1
  INSERT INTO @result SELECT @month, 2
  INSERT INTO @result SELECT @days,  3

  RETURN
END

答案 1 :(得分:0)

这个查询怎么样

Declare @FDate DateTime = '01/01/2012',
@TDate DateTime = '08/17/2014'

Select Convert(Varchar,(TotDays/365)) + 'years, ' + Convert(Varchar,(TotDays%365)/30) + '     month and ' + Convert(Varchar,(TotDays%365%30)) + ' days'
From (
    Select DATEDIFF(DAY,@FDate, @TDate) TotDays
    ) As DCal

并在此查询上方输出:

Descr
---------------------------
2years, 7 month and 19 days