简体   繁体   中英

Missing a group by statement in an aggregate sub-query

I have a query where there are multiple sales people for the same customer over time, so I only want to show the latest sales person for that given customer.

I've written the following query to show the customer and sales person for the latest date, but am getting the error "An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference."

Not sure where the group by statement would go here, assuming that's the cause so hoping someone can help out with the proper syntax.

select CUST_NAME, SALESMAN_NAME, year(invoice_Date) 
from ns.SAR_COMBINED sc
where sc.invoice_date  >= (select max(sc.invoice_date) from 
ns.SAR_COMBINED)

Thank you

you can also use row_number()

   select * from ( 
    select CUST_NAME, SALESMAN_NAME,
     year(invoice_Date) ,
    row_number() over(partition by cust_name order by invoice_date desc ) rn
    from ns.SAR_COMBINED sc) t where t.rn=1

You want a correlated subquery:

select CUST_NAME, SALESMAN_NAME, year(invoice_Date) 
from ns.SAR_COMBINED sc
where sc.invoice_date >= (select max(sc2.invoice_date)
                          from ns.SAR_COMBINED sc2
                          where sc2.cust_name = sc.cust_name
                         );

The correlation clause is the where clause in the subquery. It matches the customer in sc2 to the customer in the outer query.

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