SQL - Running Total - Year To Date, Previous Year To Date, and Last Rolling 12 Months

前端 未结 1 555
攒了一身酷
攒了一身酷 2021-01-29 12:21

Thanks for helping me out with this one! I apologize in advance for the formatting, but I think it is easy to follow.

Provided is a sample table of data. I need three

1条回答
  •  臣服心动
    2021-01-29 13:05

    VKP Raised a valid point. If missing months, we would need to fill.

    The following will generate your running total columns.

    Example

    Select *
          ,Running12       = sum(Value) over (Partition By ID Order By Date Rows Between 11 Preceding and Current Row)
          ,CalendarYTD     = sum(Value) over (Partition By ID,Year(Date) Order By Date)
          ,PrevCalendarYTD = case when month(date)<>1 then null else (Select Value from @YourTable Where ID=A.ID and date=dateadd(year,-1,A.date)) end
     From @YourTable A
     Order By ID,Date
    

    Returns

    0 讨论(0)
提交回复
热议问题