Help with query

  • I have three tables: Invoice, InvoiceCharge, and InvoiceResponse

    Invoice

    pkname
    I1Dan
    I2

    Rick

    I3John

    InvoiceCharge

    pkfk_invoicechrgdatechrgtypechrgamt
    IC1I11/1/05Bill50
    IC2

    I1

    1/2/05Rebill20

    InvoiceResponse

    pkfk_chrgrespdateresptyperespamt
    IR1IC11/2/05Check30
    IR2

    IC2

    1/3/05Cash20

    and here's a table of invoice ids that will drive a subquery:

    InvoiceList

    invoicepk
    I1
    ..

     

    I need to find the charge type of the latest invoice charge and the response type of the latest response for the latest invoice charge.

    invoiceidtotal respamount for invoicelatest charge typelatest response type
    I150RebillCash

    How can I change the following query to get the above results?

    SELECT Invoice.pk as InvoiceId,

               SUM(InvoiceResponse.respamt) as respamt

    FROM Invoice

           LEFT JOIN InvoiceCharge ON Invoice.pk = InvoiceCharge.fk_Invoice

           LEFT JOIN InvoiceResponse ON InvoiceCharge.pk = InvoiceResponse.fk_chrg

    WHERE Invoice.pk IN (select invoicepk from InvoiceList)

    Hope this is clear,

    Thanks,

    Rick


    Thanks,

    Rick Hodder

  • Hi Joe,

    Thanks for the suggestions on posting, I will try to follow them on my next post: you're right, they do things much clearer

    Thanks for the query I will try it out.

    Rick


    Thanks,

    Rick Hodder

  • try:

     

    SELECT Invoice.pk as InvoiceId, LastCharges.chrgtype, LastCharges.chrgamt, LastResponses.respamt, LastResponses.resptype

    FROM Invoice

           LEFT JOIN  (select fk_Invoice, chrgtype, chrgamt

               from InvoiceCharge ic1

                      where chrgdate = (select Max(chrgdate)

           from  InvoiceCharge ic2 

           where ic2.fk_invoice = ic1.fk_invoice) )  LastCharges

     ON Invoice.pk = LastCharges.fk_Invoice

           LEFT JOIN (select fk_chrg, resptype, respamt

               from InvoiceResponse ir1

                      where chrgdate = (select Max(respdate )

           from  InvoiceResponse ir2 

           where ir2.fk_invoice = ir1.fk_invoice) )  LastResponses

     ON LastCharges.pk = LastResponses.fk_chrg

    WHERE Invoice.pk IN (select invoicepk from InvoiceList)

    hth


    * Noel

  • Thanks Noel!

    That's just what I was looking for!

    I'll try it out!

    Thanks!

    Rick


    Thanks,

    Rick Hodder

  • Worked great, Noel - Thanks!

    Rick


    Thanks,

    Rick Hodder

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply