SQL Group By查询返回错误

时间:2014-06-12 14:47:56

标签: sql sql-server

我有一个包含以下列的SQL表:

ID, VehRegID, RenewalLetterNumber, DateLetterSent
 1    200675    1                    2014-02-01  
 4    200675    1                    2014-03-21  
 7    200675    2                    2014-04-11
 9    201175    1                    2014-02-21  
 12   201175    1                    2014-03-31  
 65   201175    2                    2014-04-11  
 88   201100    1                    2014-05-18  
 97   201100    2                    2014-05-21  

我想要完成的是:

如果VehRegID在表格中出现3次,则获取Min(DateLetterSent)并更新RenewalLetterNumber = 3

我的查询是:

SELECT VehRegID, MIN(DateLetterSent) As [EarliestDate]  
FROM tblTempRenewal  
WHERE VehRegID IN  
(SELECT VehRegID, Count(*) Total  
FROM tblTempRenewal  
GROUP BY VehRegID
HAVING Count(*) = 3)  
GROUP BY VehRegID  

我收到错误“语法更新错误”

我无法弄清楚错误的位置。有什么建议吗?

4 个答案:

答案 0 :(得分:3)

该错误是您在IN子句的子选择中返回两列的结果。您只能在该查询中返回一列,因为它是IN子句的一部分。下面我从您的子查询中删除了COUNT(*)。

SELECT VehRegID
,      MIN(DateLetterSent) As [EarliestDate]
FROM   tblTempRenewal
WHERE   VehRegID IN
        ( SELECT VehRegID

          FROM   tblTempRenewal
          GROUP
          BY     VehRegID HAVING count(*) = 3
        )
GROUP BY VehRegID

您仍然可以在不选择计数(*)的情况下使用having语句。

答案 1 :(得分:1)

我的代码格式略有不同,并在*之间添加了count()并移除了内部count,因为它没有为您做任何事情:

SELECT VehRegID
,      MIN(DateLetterSent) As [EarliestDate]
FROM   tblTempRenewal
WHERE   VehRegID IN
        ( SELECT VehRegID
          FROM   tblTempRenewal
          GROUP
          BY     VehRegID
          HAVING count(*) = 3
        )
GROUP BY VehRegID

我想知道你是否真的需要子查询。所以最终会变成:

SELECT VehRegID
,      MIN(DateLetterSent) As [EarliestDate]
FROM   tblTempRenewal
GROUP
BY     VehRegID
HAVING count(*) = 3

答案 2 :(得分:1)

从子查询中删除Count(*) TotalIN运算符中的子查询只能在Resultset中有一列。

答案 3 :(得分:0)

我们可以简化此查询吗?

SELECT VehRegID
    ,MIN(DateLetterSent)
FROM tblTempRenewal
GROUP BY VehRegID
HAVING count(0) = 3