0

我有一个要求,我的数据看起来像

Customer   OpenBal  Qty  Date
---------  -------  ---  --------
707001304  597      -48  20100414
707001304  597      -30  20100415
707001304  597      -30  20100419
707001304  597      -54  20100420

我想计算并获取数据

Customer   OpenBal  Qty  Date      ClosingBal (OpenBal+Qty)
---------  -------  ---  --------  ----------
707001304  597      -48  20100414  549
707001304  549      -30  20100415  519
707001304  519      -30  20100419  489
707001304  489      -54  20100420  435

可以帮忙,我如何汇总数据QtyDate减去OpenBal一天。ClosingBal一天将打开第二天的余额。

请指教。

4

4 回答 4

0

也许我遗漏了一些东西,但你不能只添加列+吗?

select  Customer
,       OpenBal
,       Qty
,       Date
,       OpenBal + Qty as ClosingBal
from    YourTable
于 2012-07-25T06:56:15.377 回答
0

原始表的每一行都包含相同的 OpenBal。OP 希望它是前一天的 CloseBal

对于 Oracle 10g、11g、SQL Server 2012 和 DB2 9.5,您可以使用 LAG 函数访问先前计算的值

于 2012-07-25T07:18:58.193 回答
0

这可能会有所帮助:

SELECT Customer, OpenBal, Date, SUM(OpenBal + Qty) AS Closingbal FROM Table_Name
GROUP BY Date, Customer, OpenBal
于 2012-07-25T07:12:41.383 回答
0

尝试这个:

insert into t_Customer values

(707001304,597,-48,20100414),
(707001304,597,-30,20100415),
(707001304,597,-30,20100419),
(707001304,597,-54,20100420)

select * from t_Customer

;WITH CTE as(select ROW_NUMBER() over (order by Customer) as sno,Customer,OpenBal,Qty,date,OpenBal+Qty as clsBal from t_Customer)
,CTE1 as (
select sno,Customer,OpenBal,Qty,date,clsBal from CTE where sno=1
union all
select c.sno,c.Customer,c1.clsBal,c.Qty,c.date,c1.clsBal+c.qty from CTE1 c1 inner join CTE c on c1.sno+1 =c.sno 
)
SELECT * FROM CTE1
于 2012-07-25T09:46:09.577 回答