mysql引用上一行

时间:2011-10-12 17:02:12

标签: mysql

我正在尝试使用一个mysql查询计算流失...我可以在PHP中执行此操作,但如果mysql可以执行此操作将非常有用。

这是我的疑问:

SELECT 
  bill_date_bil,
  account_number_bil,
 SUM(amount_bil)


FROM
  billing_bil 
WHERE account_number_bil = 20017
  AND type_bil <> 'CA' 
  AND type_bil <> 'CK' 
GROUP BY period (bill_date_bil)
ORDER BY bill_date_bil ASC

这就是我得到的:

bill_date_bil  account_number_bil  sum(amount_bil)
-------------  ------------------  ---------------
2007-09-01                  20017        3498.5000
2007-10-01                  20017        8248.5000
2007-11-01                  20017        9886.0000
2007-12-01                  20017        9411.0000
2008-01-01                  20017        9411.0000
2008-02-01                  20017        9411.0000
2008-03-01                  20017       -6151.5000
2008-04-01                  20017        6118.5400
2008-05-01                  20017       11171.9800
2008-06-01                  20017        6434.3800
2008-07-01                  20017        6434.3800

我想提供另一个专栏,让我了解当前账单与前几个月的账单之间的区别。

思想?

这就是我需要的:

bill_date_bil   account_number_bil  sum(amount_bil) churn
-------------   ------------------  --------------- 
9/1/2007    20017   3498.5                         0
10/1/2007   20017   8248.5                        4750
11/1/2007   20017   9886                           1637.5
12/1/2007   20017   9411                        -475
1/1/2008    20017   9411                           0
2/1/2008    20017   9411                           0
3/1/2008    20017   -6151.5                       -15562.5
4/1/2008    20017   6118.54                         12270.04
5/1/2008    20017   11171.98                            5053.44
6/1/2008    20017   6434.38                         -4737.6
7/1/2008    20017   6434.38                         0

1 个答案:

答案 0 :(得分:2)

使用此:

SET @sum_bill=0;
SELECT 
  bill_date_bil,
  account_number_bil,
 SUM(amount_bil),
@sum_bill := @sum_bill+SUM(amount_bil)


FROM
  billing_bil 
WHERE account_number_bil = 20017
  AND type_bil <> 'CA' 
  AND type_bil <> 'CK' 
GROUP BY period (bill_date_bil)
ORDER BY bill_date_bil ASC