Sqlserver
 sql >> डेटाबेस >  >> RDS >> Sqlserver

जारी किए गए चालानों के भुगतान के लिए कुल चल रहा है

with DateRange as
(
  select convert(date, '2020-11-01') as DateValue
  union all
  select dateadd(day, 1, dr.DateValue)
  from DateRange dr
  where dr.DateValue < '2020-11-30'
),
InvoicedTotal as
(
  select dr.DateValue,
         isnull(sum(i.Total), 0) as Invoiced
  from DateRange dr
  left join Invoices i
    on i.InvoiceDate = dr.DateValue
  group by dr.DateValue
),
PaidTotal as
(
  select dr.DateValue,
         isnull(sum(case
                      when i.InvoiceDate between '2020-11-01' and '2020-11-30' -- check if matching invoice was found
                      then p.Total                 -- YES = include Total amount in sum
                      else 0                       -- NO  = exclude total amount from sum
                    end), 0) as Paid
  from DateRange dr
  left join Payments p
    on p.PaymentDate = dr.DateValue
  left join Invoices i
    on  i.InvoiceId = p.InvoiceId -- check for invoice related to payment
  group by dr.DateValue
)
select convert(varchar(10), dr.DateValue, 102) as [YYYY.MM.DD],
       it1.Invoiced as [Invoiced],
       it3.Invoiced as [CumInvoiced],
       pt1.Paid as [Paid],
       pt3.Paid as [CumPaid],
       it3.Invoiced - pt3.Paid as [RunningTotal]
from DateRange dr
join InvoicedTotal it1
  on it1.DateValue = dr.DateValue
join PaidTotal pt1
  on pt1.DateValue = dr.DateValue
cross apply ( select sum(it2.Invoiced) as Invoiced
              from InvoicedTotal it2
              where it2.DateValue <= dr.DateValue ) it3
cross apply ( select sum(pt2.Paid) as Paid
              from PaidTotal pt2
              where pt2.DateValue <= dr.DateValue ) pt3
order by dr.DateValue;

Fiddle द्वारा milo2011




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. SQL सर्वर 2017 चरण दर चरण स्थापना -1

  2. SQL सर्वर में APPROX_COUNT_DISTINCT () कैसे काम करता है

  3. Azure डेटा स्टूडियो पर SQL सर्वर एजेंट एक्सटेंशन स्थापित करें

  4. बीसीपी आयात त्रुटि कास्ट विनिर्देश के लिए अमान्य वर्ण मान

  5. संग्रहीत कार्यविधि सामग्री तक केवल पहुंच पढ़ें