Lag Lead计算一段时间内订阅的开始和结束数量

时间:2018-04-25 05:49:20

标签: sql lag window-functions lead

我正在尝试构建一个输出表,如下所示。有人可以帮助我如何使用滞后线或其他窗口函数来解决它吗?

Start= End from previous month
Net= new- churn
End = Start + Net

INPUT 

month   year    new churn   
2      2012     114     0   
3      2012     143     20  
4      2012     221     43  
5      2012     197     74  
6      2012     234     122 
7      2012     276     138 
8      2012     278     200 


OUTPUT


month   year    Start   new churn   Net End
2      2012     0       114     0   114 114
3      2012     114     143     20  123 237
4      2012     237     221     43  181 418
5      2012     418     197     74  125 543
6      2012     543     234     122 116 659
7      2012     659     276     138 150 809
8      2012     809     278     200 90  899

4 个答案:

答案 0 :(得分:0)

不确定如何计算开始。你说Start将在上个月结束,但没有提到它需要的列。但我认为你需要一些东西如下。

resource

答案 1 :(得分:0)

试试这个:

DECLARE @tab1 TABLE(month INT, year INT,new INT, churn INT)

INSERT INTO @tab1 VALUES
(2,2012,114,0  )
,(3,2012,143,20 )
,(4,2012,221,43 )
,(5,2012,197,74 )
,(6,2012,234,122)
,(7,2012,276,138)
,(8,2012,278,200)

SELECT [T1].[month],[T1].[Year]
    ,ISNULL(SUM([T2].new-[T2].churn) OVER(ORDER BY [T1].[Year], [T1].[month]),0)Start
    ,[T1].new, [T1].churn, [T1].new-[T1].churn AS net
    ,([T1].new-[T1].churn)+ISNULL(SUM([T2].new-[T2].churn) OVER(ORDER BY [T1].[Year], [T1].[month]),0) [End]
From @tab1 T1
LEFT JOIN @tab1 T2 ON T1.month = t2.month+1

<强>输出:

month   Year    Start   new churn   net End
2       2012    0       114 0       114 114
3       2012    114     143 20      123 237
4       2012    237     221 43      178 415
5       2012    415     197 74      123 538
6       2012    538     234 122     112 650
7       2012    650     276 138     138 788
8       2012    788     278 200     78  866

答案 2 :(得分:0)

您可以尝试此查询。

;WITH CTE AS(
    SELECT *,(new- churn) as 'Net' 
    from T1
)
SELECT t1.[month],
       t1.[Year],
       coalesce(lag([End]) OVER(order by [year],[month]),0) 'Start',
       t1.new,
       t1.churn,
       t1.Net,
       t1.[End]
FROM (
    SELECT t1.*,coalesce(SUM(t2.Net) over(order by t2.[year],t2.[month]),0) +t1.net as 'End'
    From  CTE t1
    LEFT JOIN CTE t2 ON T1.[month] = t2.[month]+1
) t1

sqlfiddle:http://sqlfiddle.com/#!18/6a544/1

答案 3 :(得分:0)

我想你想要:

select i.*,
       sum(new) over (order by year, month) as start,
       (new - churn) as net,
       sum(new - churn) over (order by year, month) as end
from input i;

Here是一个SQL小提琴。