如何在子查询中使用group by / having子句?

时间:2013-09-17 15:24:33

标签: sql sql-server

我正在尝试使用group by和having子句从以下子查询中提取ClientID但是我收到以下错误:

  

Msg 116,Level 16,State 1,Line 1
  当未引入子查询时,只能在选择列表中指定一个表达式   存在。

查询:

select 
    ClientID 
from 
    SurveyResponses 
where 
     ClientID in (select ClientID, count (surveyresponseid) 
                  from SurveyResponses
                  where SurveyID in (1988,1989,2750,3206,15561) 
group by 
     ClientID
having count (SurveyResponseID) > 1) and SurveyID = 1989

5 个答案:

答案 0 :(得分:0)

你在子查询中拉了两列,只能拉一个,因为你告诉sql,检查调查回复计数中的客户ID和SurveyResponses表中的clientID。

试试这个,它是未经测试的

select ClientID from SurveyResponses 
where ClientID in (select ClientID  from SurveyResponses
where SurveyID in (1988,1989,2750,3206,15561) 
group by ClientID
having count (SurveyResponseID) > 1) and SurveyID = 1989

答案 1 :(得分:0)

您可以尝试这样: -

select ClientID from SurveyResponses where ClientID in
(select ClientID from SurveyResponses
where SurveyID in (1988,1989,2750,3206,15561) 
group by ClientID
having count (SurveyResponseID) > 1) and SurveyID = 1989

答案 2 :(得分:0)

select 
    ClientID 
from 
    SurveyResponses 
where 
     ClientID in (select ClientID,  
                  from SurveyResponses
                  where SurveyID in (1988,1989,2750,3206,15561) 
group by 
     ClientID
having count (SurveyResponseID) > 1) and SurveyID = 1989

此子查询无效,因为您选择了多个字段ClientID, count (surveyresponseid)。如果您要在subquery Where In条件中处理多个字段,请尝试此操作。Handling multiple columns

答案 3 :(得分:0)

所有其他答案都可以正常使用,您也可以使用EXISTS语法:

SELECT clientID
FROM SurveyResponses
WHERE EXISTS (
         SELECT * 
         FROM SurveyResponses SR 
         WHERE SR.SurveyId IN (1988, 1989, 2759, 3206, 15561) 
               AND SR.ClientId = ClientID)
GROUP BY ClientID
HAVING COUNT(SurveyResponseID) > 1 AND SurveyID = 1989

答案 4 :(得分:-1)

从select子句

中删除 count()
   select ClientID from SurveyResponses where ClientID in
    (select ClientID from SurveyResponses
    where SurveyID in (1988,1989,2750,3206,15561) 
    group by ClientID
    having count (SurveyResponseID) > 1) and SurveyID = 1989