简体   繁体   中英

How do you use a group by / having clause in a sub-query for?

I'm trying to pull the ClientID from the following sub-query with a group by and having clause but I get the following error:

Msg 116, Level 16, State 1, Line 1
Only one expression can be specified in the select list when the subquery is not introduced w ith EXISTS.

Query:

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

You are pulling two columns in your sub query and can only pull one, because you are telling sql, check where client ID exists in the count of survey responses AND the clientIDs in the SurveyResponses table.

Try this, it is untested

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

You may try like this:-

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
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

This subquery is not valid cause you are selecting multiple fields ClientID, count (surveyresponseid) . If you want to handle multiple fields in subquery for Where In condition try this . Handling multiple columns

All the other answers work fine, you could also use the EXISTS syntax:

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

Remove the count() from the select clause

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM