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

前端 未结 7 1676
庸人自扰
庸人自扰 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:40

    -----Alternative way------

    select 
        d.firstOfMonth,
        MONTH(d.firstOfMonth) as Mon,
        YEAR(d.firstOfMonth) as Yr, 
        t.TransactionValue
    from (
        select 
            dateadd( month, inMonths - 1, '1/1/2009') as firstOfMonth 
            from (
                values (1), (2), (3), (4), (5), (7), (8), (9), (10), (11), (12)
            ) Dates(inMonths)
    ) d
    outer apply (
        select top 1 TransactionValue
        from Transactions
        where TransactionDate <= d.firstOfMonth
        order by TransactionDate desc
    ) t
    

提交回复
热议问题