按列分组和按列聚合

时间:2012-07-25 06:27:23

标签: sql sql-server sql-server-2008 group-by aggregate-functions

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

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

可以提供帮助,如何将Qty上的数据汇总到Date并从OpenBal减去一天。 ClosingBal一天将为第二天开放余额。

请告知。

4 个答案:

答案 0 :(得分:0)

也许我错过了什么,但你不能只用+添加列吗?

select  Customer
,       OpenBal
,       Qty
,       Date
,       OpenBal + Qty as ClosingBal
from    YourTable

答案 1 :(得分:0)

这可能有所帮助:

SELECT Customer, OpenBal, Date, SUM(OpenBal + Qty) AS Closingbal FROM Table_Name
GROUP BY Date, Customer, OpenBal

答案 2 :(得分:0)

  
    

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

  

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

答案 3 :(得分: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