Multi Table Query With Max Per Grouping

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mcfly1204
    New Member
    • Jul 2007
    • 233

    Multi Table Query With Max Per Grouping

    I am looking to grab data from 3 tables, customers, contacts, and invoice. What I am looking to attain is the customer name, the primary contact name, and the oldest due date of the customer's invoices.

    Code:
    select distinct CUST.CustName, CUST.CustKey, CON.Name, min(INVC.DueDate)
    from Customer CUST JOIN
    	Contact CON ON CON.CntctKey=CUST.PrimaryCntctKey JOIN
    	Invoice INVC ON INVC.Custkey=CUST.CustKey
    where INVC.Balance>.000 AND GetDate()>INVC.DueDate
    group by CUST.CustKey, INVC.DueDate, CUST.CustName, CON.Name
    I would imagine I would need to use subqueries, but I get thrown by needing the minimum invoice due date per customer.

    **edit**

    Code:
    select min(duedate), INVC.CustKey, CUST.CustName, CON.Name
    from Invoice INVC JOIN
    	Customer CUST ON CUST.CustKey=INVC.CustKey JOIN
    	Contact CON ON CON.CntctKey=CUST.PrimaryCntctKey
    where balance > .000 and INVC.companyid = 'QMC' and GetDate()>DueDate
    group by INVC.CustKey, CUST.CustName, CON.Name
    Last edited by mcfly1204; Mar 26 '09, 06:19 PM. Reason: solution found
  • ck9663
    Recognized Expert Specialist
    • Jun 2007
    • 2878

    #2
    Will this work:

    Code:
    select CUST.CustName, CUST.CustKey, CON.Name, min(INVC.DueDate)
    from Customer CUST JOIN
        Contact CON ON CON.CntctKey=CUST.PrimaryCntctKey JOIN
        Invoice INVC ON INVC.Custkey=CUST.CustKey
    where INVC.Balance>.000 AND GetDate()>INVC.DueDate
    group by CUST.CustKey, CUST.CustName, CON.Name

    --- CK

    Comment

    • mcfly1204
      New Member
      • Jul 2007
      • 233

      #3
      Yes, that query works too. Each query uses the same execution plan as well.

      Comment

      Working...