【问题标题】:Group Function is not allowed here SQL此处不允许使用 Group Function SQL
【发布时间】:2016-01-29 05:08:49
【问题描述】:

我有这样的表:

出席(offering_id,visitor_id, regstr_date,amount_paid) 报价(offering_id,teacher_id) 老师(teacher_id,teacher_firstname,teacher_lastname,start_date)

一位访客可能会参加两次或更多次。我想从出勤中检索visitor_id,regstr_date,total amount_paid,average amount_paid,其中提供ID为30,40或50,教师的开始日期小于任何访问者的最新regstr_date,每个访问者的平均amount_paid小于600。我的代码是如下:

select 
    distinct(a.visitor_id) as v_id ,
    max(a.regstr_date) as reg_date,
    sum(a.amount_paid) as total_pay,
    count(a.regstr_date) as attendance_count,
    avg(a.amount_paid) as average_paid
from 
    attendance a, teacher t, offer o  
where  
    a.offering_id = o.offering_id 
    and o.teacher_id = t.teacher_id 
    and a.offering_id in ('30', '40', '50') 
    and max(a.regstr_date) > t.start_date
group by 
    a.visitor_id
having 
    avg (a.amount_paid) <= 600;

但它表明这里不允许使用组功能。如果可能的话,你能帮我解决这个问题吗?

【问题讨论】:

  • 你不需要使用 distinct
  • 没有区别,效果也不好
  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI JOIN 语法-92 SQL 标准(20 多年前),不鼓励使用它
  • @Programmer 你用的是什么RDBMS
  • max(a.regstr_date) > t.start_date 应该在有子句中。

标签: sql group-by oracle-sqldeveloper having-clause


【解决方案1】:

这个查询是为 MS-SQL 服务器编写的

select  a.visitor_id as v_id ,
max(a.regstr_date) as reg_date,
sum(a.amount_paid) as total_pay,
count(a.regstr_date) as attendance_count,
avg(a.amount_paid) as average_paid
from attendance a Inner Join  offer o   on a.offering_id = o.offering_id
inner join  teacher t on t.teacher_id = o.teacher_id
where a.offering_id in('30','40','50') 
group by a.visitor_id,t.start_date
having avg (a.amount_paid)<=600 and  max(a.regstr_date)>t.start_date;

【讨论】:

  • 非常感谢,这对我也有用@halit kardeş
猜你喜欢
  • 2020-03-31
  • 2021-12-20
  • 2018-05-15
  • 2023-03-04
  • 2014-05-28
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多