列在HAVING子句中无效,因为它不包含在聚合函数或GROUP BY中

时间:2016-04-30 13:10:55

标签: sql filter

我正在尝试使我的列等于过滤器使用,但问题是它给出了此错误消息:

column is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY

当我尝试在select和group中添加过滤器时说:

Column names in each view or function must be unique

因为列和过滤器都是相同的:

专栏:

     userTable.userid

过滤器:

  user_filter.userid

这是我的代码:

SELECT  DISTINCT 
userId,
username,
sum(userItem)
from userTable inner join user_filter
on userTable.userName =  user_filter.userName 
group by userId,
username,
having  userTable.userId =  user_filter.userId

1 个答案:

答案 0 :(得分:0)

您不需要Having子句只需在Where子句中添加另一个过滤器

SELECT userid, 
       username, 
       Sum(useritem) 
FROM   usertable 
       INNER JOIN user_filter 
               ON usertable.username = user_filter.username 
                  AND usertable.userid = user_filter.userid 
GROUP  BY userid, 
          username 

同样DISTINCT也是多余的,因为在Group by已使用select