Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

SQL Server Alokasi jumlah dalam tagihan

WITH  cl AS
(select o.LINEID, o.BILL, o.[Total Amount], 
(select SUM([Total Amount]) from bills t where o.BILL = t.BILL and o.LINEID >= t.LINEID) as 'sum_total_ammount'
from bills o inner join payment p on o.BILL = p.BILL)

select o.LINEID, o.BILL, o.[Total Amount], 
case when p.[Paid Amount] >= sum_total_ammount then o.[Total Amount] 
else (o.[Total Amount] - sum_total_ammount + p.[Paid Amount]) end as 'Allocated Amount'
from cl o inner join payment p on o.BILL = p.BILL
and (o.[Total Amount] - sum_total_ammount + p.[Paid Amount]) > 0

Berikut Demo di SqlFiddle .




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara memperbarui baris dengan tanggal acak

  2. Ketahui Cara Memulihkan Tabel yang Dihapus di SQL Server 2012 Tanpa Cadangan

  3. Periksa Status Antrian Surat Database di SQL Server (T-SQL)

  4. Pulihkan Database SQL Server - gagal:38(Mencapai akhir file.)

  5. Bagaimana cara menemukan indeks yang dinonaktifkan pada SQL server 2008