Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何在SQL Server中生成使用其前置值计算的列_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql server 如何在SQL Server中生成使用其前置值计算的列

Sql server 如何在SQL Server中生成使用其前置值计算的列,sql-server,sql-server-2008,Sql Server,Sql Server 2008,比如说 Amount ReceivedAmount PendingAmount --------------------------------------- 1000 400 600 600 400 200 如何获取金额列中的600值 表结构是 1. BillID,Amount,Date from table1 及 收到的金额可以是多次,我想从Amount-SUMReceivedAm

比如说

Amount   ReceivedAmount   PendingAmount
---------------------------------------
 1000         400             600       
  600         400             200
如何获取金额列中的600值

表结构是

1. BillID,Amount,Date from table1


收到的金额可以是多次,我想从Amount-SUMReceivedAmount中获得未决金额

您需要首先加入下面的表1和表2。我在CTE中这样做了。然后对上述结果进行自联接以获得累积值

2. BillReceive,ReceiveDate,ReceivedAmount from table2
 ; with cte as 
(
 select 
     billid, 
     amount,
     receivedamount, 
     r=row_number() over (partition by t1.billid order by ReceiveDate asc)
 from
  table1 t1 join table2 t2
      on t1.billid=t2.BillReceive
 )

 select 
   amount=max(c1.amount)+max(c1.receivedamount)-sum(c2.receivedamount),
   receivedamount=max(c1.receivedamount),
   pendingamount=max(c1.amount)-sum(c2.receivedamount)
 from 
   cte c1 left join cte c2 
      on c2.r<=c1.r and c2.billid=c1.billid
 group by c1.billid,c1.r