I have a customer, order and Sales Agent table. I am trying to get the last order for customers using max date on the orders table. This is what I have so far.
SELECT ct.CSNAME, ct.CSADDR1, ct.CSCITY, ct.CSST, ct.CSZIP, ct.CSPHONE, ct.CSCODE, ot.LastOrderDate, SALESAGENT.SANAME
FROM CUSTOMER AS ct INNER JOIN
(SELECT CSCODE, MAX(ORDER_DATE) AS LastOrderDate
FROM ORDERS
GROUP BY CSCODE) AS ot
ON ct.CSCODE = ot.CSCODE INNER JOIN
SALESAGENT ON ct.SACODE = SALESAGENT.SACODE
WHERE (ot.LastOrderDate BETWEEN '01/01/2010' AND '08/01/2015') AND (ct.CSTYPE = 'A')
ORDER BY ct.CSNAMEindent preformatted text by 4 spaces
This query works great but I need to add a couple things. First in the Orders table there is a field called PLT_NO and I only want orders that have a '2' in that field. Secondly in the Orders table I want to select a field called TOTAL_AMT. So when the query selects the MaxDate record for each customer it would also pull the value of the TOTAL_AMT field for that record. I've tried in the query below but I get this error Column 'ORDERS.TOTAL_AMT' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
SELECT ct.CSNAME, ct.CSADDR1, ct.CSCITY, ct.CSST, ct.CSZIP, ct.CSPHONE, ct.CSCODE, ot.LastOrderDate, ot.TOTAL_AMT, SALESAGENT.SANAME
FROM CUSTOMER AS ct INNER JOIN
(SELECT CSCODE, TOTAL_AMT, PLT_NO, MAX(ORDER_DATE) AS LastOrderDate
FROM ORDERS
GROUP BY CSCODE) AS ot ON ct.CSCODE = ot.CSCODE INNER JOIN
SALESAGENT ON ct.SACODE = SALESAGENT.SACODE
WHERE (ot.LastOrderDate BETWEEN '01/01/2010' AND '08/01/2015') AND (ct.CSTYPE = 'A') AND PLT_NO = '2'
I am at a complete loss as to how to get the Plt_No = 2 in the Where clause and the Total_Amt in the select for Orders. Any help would be much appreciated.
Thanks,
Stacy