[英]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: 我试图从下面的子查询中使用group by和having子句拉出
ClientID
,但出现以下错误:
Msg 116, Level 16, State 1, Line 1
消息116,第16级,状态1,第1行
Only one expression can be specified in the select list when the subquery is not introduced w ith EXISTS.未通过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. 您要在子查询中提取两列,而只能提取一列,因为您要告诉sql,请检查调查响应计数中的客户端ID和SurveyResponses表中的clientID在哪里。
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)
. 此子查询无效,因为您要选择多个字段
ClientID, count (surveyresponseid)
。 If you want to handle multiple fields in subquery
for Where In
condition try this . 如果要
Where In
条件为Where In
条件的subquery
处理多个字段,请尝试此操作。 Handling multiple columns 处理多列
All the other answers work fine, you could also use the EXISTS
syntax: 所有其他答案都可以正常工作,您也可以使用
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
Remove the count() from the select clause 从选择子句中删除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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.