How to Determine Values for Missing Months based on Data of Previous Months in T-SQL

前端 未结 7 1709
庸人自扰
庸人自扰 2020-12-09 14:24

I have a set of transactions occurring at specific points in time:

CREATE TABLE Transactions (
    TransactionDate Date NOT NULL,
    TransactionValue Intege         


        
7条回答
  •  误落风尘
    2020-12-09 14:45

    If you do this type of analysis often, you might be interested in this SQL Server function I put together for exactly this purpose:

    if exists (select * from dbo.sysobjects where name = 'fn_daterange') drop function fn_daterange;
    go
    
    create function fn_daterange
       (
       @MinDate as datetime,
       @MaxDate as datetime,
       @intval  as datetime
       )
    returns table
    --**************************************************************************
    -- Procedure: fn_daterange()
    --    Author: Ron Savage
    --      Date: 12/16/2008
    --
    -- Description:
    -- This function takes a starting and ending date and an interval, then
    -- returns a table of all the dates in that range at the specified interval.
    --
    -- Change History:
    -- Date        Init. Description
    -- 12/16/2008  RS    Created.
    -- **************************************************************************
    as
    return
       WITH times (startdate, enddate, intervl) AS
          (
          SELECT @MinDate as startdate, @MinDate + @intval - .0000001 as enddate, @intval as intervl
             UNION ALL
          SELECT startdate + intervl as startdate, enddate + intervl as enddate, intervl as intervl
          FROM times
          WHERE startdate + intervl <= @MaxDate
          )
       select startdate, enddate from times;
    
    go
    

    it was an answer to this question, which also has some sample output from it.

提交回复
热议问题