SQL GROUP BY错误

时间:2011-11-16 08:52:46

标签: sql

我正在尝试从sql查询中检索结果,该查询将 Table1 中的重复用户ID返回到 Table3

以下是我的sql语句:

INSERT INTO Table3(UserID, Name, Issue) 
   SELECT t1.UserID, t1.Name, 'Duplicated userid found in Table1' 
   FROM Table1 t1 
   GROUP BY t1.UserUD  
   HAVING COUNT(*) > 1

但是,我尝试在我的数据源中运行它后收到以下错误:

  

列'Table1.Name'在select语句列表中无效,因为它不包含在聚合函数或GROUP BY中   条款

我可以知道我的错误在哪里吗?

谢谢

3 个答案:

答案 0 :(得分:4)

INSERT INTO Table3(UserID, Name, Issue) 
SELECT t1.UserID, t1.Name, 'Duplicated userid found in Table1' 
FROM Table1 t1 
GROUP BY t1.UserUD, t1.Name
HAVING COUNT(t1.UserID) > 1

您错过了

组中的字段

答案 1 :(得分:3)

您需要按照您选择中不属于聚合函数的所有列进行分组,例如,在您的情况下:

INSERT INTO Table3(UserID, Name, Issue)
SELECT t1.UserID, t1.Name, 'Duplicated userid found in Table1'
FROM Table1 t1 
GROUP BY t1.UserID, t1.Name
HAVING COUNT(*) > 1

甚至,如果您的姓名也可能不会重复:

INSERT INTO Table3(UserID, Name, Issue)
SELECT t1.UserID, MAX(t1.Name), 'Duplicated userid found in Table1'
FROM Table1 t1 
GROUP BY t1.UserID
HAVING COUNT(*) > 1

答案 2 :(得分:0)

  1. t1.userUD组而不是ID似乎是可疑的

  2. 但是,非常确定您需要按t1.UserID,t1.Name进行分组。它不会改变查询的逻辑。