简体   繁体   English

在汇总子查询中缺少分组依据语句

[英]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." 我编写了以下查询,以显示客户和销售人员的最新日期,但收到错误消息:“除非在HAVING子句或选择列表中包含的子查询中,否则聚合可能不会出现在WHERE子句中,并且正在汇总的列是外部参考。”

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. 不知道group by语句在这里会去哪里,因为这就是原因,所以希望有人可以提供正确的语法帮助。

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() 您还可以使用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. 相关子句是子查询中的where子句。 It matches the customer in sc2 to the customer in the outer query. 它将sc2中的客户与外部查询中的客户匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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