聚合函数/分组依据 - 无效列错误

时间:2013-12-13 11:52:15

标签: sql sql-server asp-classic

使用经典ASP和MS-SQL server 2008

我要做的是选择重复记录,并对它们进行计数,以便我可以更新第一个并删除其余记录。

我的查询选择重复项OK但是当我尝试引入计数时它会停止使用消息“列'calendar.id'在选择列表中无效,因为它不包含在聚合函数或者GROUP BY子句。“

我试图重写这个并将计数添加到第二个SELECT并将id添加到GROUP BY(以及我能想到的这种事情的多种组合,但我仍然会遇到错误。我看到了答案at stackoverflow上的解决方案似乎有点复杂而且不太适用(或者我不是在寻找合适的东西)

我在哪里错了? (这也是在一个小表中查找和编辑重复项的最佳方法(200k行?)

Dim strSQL_dup, rsSQL_dup, SQL_dupRecords, RecCount


            strSQL_dup = "SELECT id, COUNT(id) AS RecCount FROM calendar WHERE start_date IN ( SELECT start_date FROM calendar WHERE pId = '" & pId & "' GROUP BY start_date HAVING (COUNT(start_date ) > 1) )  "
            Set rsSQL_dup = conn.Execute(strSQL_dup)

            While Not rsSQL_dup.EOF
                If RecCount = 1 Then
                        'will eventually update the row 
                        response.write(rsSQL_dup("id")) ' id of first'
                Else
                        'will eventually delete the other rows
                        response.write(rsSQL_dup("id")) ' id of subsiquet rows
                End If
            rsSQL_dup.MoveNext
            Wend

2 个答案:

答案 0 :(得分:1)

问题是COUNT是一个聚合函数,因此传递给它的任何参数都需要在GROUP BY子句中。

如果id本身是您确定唯一性的关键,则可以将查询更改为

SELECT id, COUNT(id) AS RecCount FROM calendar group by id having count(id) > 1

如果日期对过滤您的数据子集很重要,例如要仅在特定时间段内搜索,可以将其包含在WHERE子句中。另一方面,如果date和id一起确定唯一性,则需要在GROUP BY子句中包含这两个字段。

答案 1 :(得分:1)

您似乎在主查询中缺少GROUP BY:

SELECT id, COUNT(id) AS RecCount 
 FROM calendar 
WHERE start_date IN (SELECT start_date FROM calendar 
                     WHERE pId = '" & pId & "' 
                     GROUP BY start_date 
                     HAVING (COUNT(start_date ) > 1) )
GROUP BY clalendar.id

(最后一行当然可以是GROUP BY id我只想强调最后一行和第一行之间的联系)

相关问题