简体   繁体   中英

Is there a way to conditionally sum date ranges in an Access SQL query?

I have a table "ORDERHIST" containing transaction data with client IDs, date of purchase, date payment was received, different transaction types, and the invoice amount. I'm trying to create a table that shows the sum of all outstanding invoice amounts for each business day. I only want transactions with a TypeCode of SERV or CONS included in the query.

Data sample:

CliendID    PurchaseDate    PaymentDate TypeCode    InvoiceAmt
ID1         1/3/2019        1/4/2019    SERV        430
ID2         1/3/2019        1/4/2019    PART        200
ID1         1/4/2019        1/9/2019    SERV        480
ID3         1/7/2019        1/8/2019    CONS        140
ID2         1/7/2019        1/9/2019    CONS        180
ID3         1/8/2019        1/9/2019    SERV        250
ID1         1/9/2019        1/10/2019   CONS        180

Essentially the logic should be sum if (PurchaseDate <= Date) and (PaymentDate >= Date) and (TypeCode = SERV or TypeCode = CONS).

Expected Result:

Date        OutstandingBal
1/3/2019    430
1/4/2019    910
1/7/2019    800
1/8/2019    1050
1/9/2019    1090

The resulting table dates can either be every day or only on days with transactions, whichever is easier.

OutwardBal=sum(iif((PurchaseDate <= Date) and (PaymentDate >= Date) and (TypeCode = SERV or TypeCode = CONS), invoiceAmt,0))

This is tricky. You need to start with a list of dates. Then I would go for a correlated subquery in MS Access:

select d.dte,
       (select sum(oh2.invoiceamt)
        from orderhist as oh2
        where oh2.PurchaseDate <= d.dte and
              oh2.PaymentDate >= d.dte and
              oh2.TypeCode in ("SERV", "CONS")
       ) as outstandingbalance
from (select distinct purchasedate as dte
      from orderhist
     ) as d
group by d.dte;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM