Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

SQL – Total cumulé – Cumul de l'année, Cumul de l'année précédente et 12 derniers mois glissants

Ce qui suit générera vos colonnes de total cumulé.

Exemple

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

Retours