SQL 同比环比增长率计算

时间:2024-03-16 14:54:06

SQL 同比环比增长率计算

同比:

SELECT DISTINCT
    B.dateM,B.dateY,B.Total,B.Total+B.Total*AVG( B.per ) OVER ( PARTITION BY B.dateM ) as predictionTotal
    ,    AVG( B.per ) OVER ( PARTITION BY B.dateM ) AS [AvgPer]
    ,MAX( B.per ) OVER ( PARTITION BY B.dateM ) AS [MaxPer]
    ,Min( B.per ) OVER ( PARTITION BY B.dateM ) AS [MinPer] from 
    (SELECT A.dateM,A.dateY
 ,A.[Total] - A.[PreviousTotal] as GrowthTotal,(A.[Total] - A.[PreviousTotal])/A.[PreviousTotal] as per,A.[Total]
,    A.[Month]
FROM 
(
select s.dateM,dateY,COUNT(*) OVER ( PARTITION BY s.dateM ) AS [Month],s.[Total]  AS [Total]
,     LAG( s.[Total] ) OVER ( PARTITION BY s.dateM ORDER BY s.dateY ) AS [PreviousTotal] 
        from (SELECT datepart(mm,[month]) as dateM, datepart(yyyy,[month]) as dateY,sum([Total]) Total
FROM [KS_DataBase3.0_QJ].[dbo].[KS_MonthVbt] where [Month]>='2017' and [Month]<'2019'
GROUP BY [month]) s 
) AS A
) B 

 

SQL 同比环比增长率计算

环比计算比较简单

SQL 同比环比增长率计算

 

  SELECT o.*
FROM (SELECT o.*, 
             (total / LAG(total) OVER (ORDER BY month) - 1) as growth
      FROM [KS_DataBase3.0_QJ].[dbo].[KS_MonthVbt] o
     ) o
WHERE [Month] <= '2019-10-01'
ORDER BY [Month];