【发布时间】:2015-07-13 11:30:12
【问题描述】:
我需要计算indebtedness 列的值,以便当openingBalance !=0 then indebtedness = openingBalnce+SalesTotal-SalesReturn 时。但是,当之前的monthSales 的openingBalnce = 0 then indebtedness = indebtedness 与相同的SalesID。如果previous value = 0 得到previous value 并继续得到previous value 直到在此列中有值:
SalesMonth SalesID openingBalance SalesTotal SalesReturn Indebtednes
1 1 352200 0 5600 NULL
1 2 50000 1100 0 NULL
1 3 9500 6000 0 NULL
2 1 0 0 1200 NULL
2 2 0 300 0 NULL
2 3 0 500 1000 NULL
3 1 0 600 0 NULL
3 2 0 200 0 NULL
3 3 0 0 10 NULL
.
.
.
12 1 0 0 0 NULL
12 2 0 0 0 NULL
12 3 0 0 0 NULL
输出如下:
when openingBalance !=0 then Indebtednes=openingBalnce+SalesTotal-SalesReturn
when openingBalnce =0 then Indebtednes=Indebtednes (of the previous
month of the same SalesID)+SalesTotal-SalesReturn.
And this is the output i want.
SalesMonth SalesID openingBalance SalesTotal SalesReturn Indebtednes
---------- ------- -------------- ---------- ----------- ------------
1 1 352200 0 5600 346600
------------------------------------------------------------------------
1 2 50000 1100 0 51100
------------------------------------------------------------------------
1 3 9500 6000 0 15500
------------------------------------------------------------------------
2 1 0 0 1200 345400
------------------------------------------------------------------------
2 2 0 300 0 51400
------------------------------------------------------------------------
2 3 0 500 1000 15000
------------------------------------------------------------------------
3 1 0 600 0 346000
------------------------------------------------------------------------
3 2 0 200 0 51600
-----------------------------------------------------------------------
3 3 0 0 10 14990
-----------------------------------------------------------------------
.
.
.
12 1 0 0 0 NULL
----------------------------------------------------------------------
12 2 0 0 0 NULL
----------------------------------------------------------------------
12 3 0 0 0 NULL
【问题讨论】:
-
你也可以添加预期的输出
-
对于 salesMonth=1 和 SalesID=1 Indebtednes =346600
-
我的意思是预期的样本输出,其数据基于问题中的上述样本输入。您可以编辑问题并添加详细信息
-
for salesMonth=1 and SalesID=1 Indebtednes =346600 salesMonth=2 and salesID =1 indebtedness = 346600 and the same case with SalesID =2,3 when openingBalnce !=0 then indebtedness=openingBalnce+SalesTotal -SalesReturn 但是,当openingBalance = 0 获取相同SalesID 的上个月的Indebtednes 时,问题是如果上一个indebtedness 为0 获取上个月的值并继续获取上个月的上一个值直到得到值,怎么办这???
标签: sql-server-2008 recursive-query