【问题标题】:How do you use a group by / having clause in a sub-query for?如何在子查询中使用 group by / having 子句?
【发布时间】:2013-09-22 03:02:21
【问题描述】:

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

消息 116,第 16 级,状态 1,第 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

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    你可以这样尝试:-

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

      您在子查询中拉出两列,并且只能拉出一列,因为您告诉 sql,检查客户 ID 存在于调查响应计数中的位置以及 SurveyResponses 表中的客户 ID。

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

      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
      

      【讨论】:

      • 你应该在你的代码 sn-ps 之前使用> char - 使它更难阅读,禁用语法突出显示......
      • 啊,我不知道。谢谢。
      【解决方案3】:
      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

      【讨论】:

        【解决方案4】:

        所有其他答案都可以正常工作,您也可以使用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
        

        【讨论】:

          【解决方案5】:

          从 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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-08-15
            • 1970-01-01
            • 2023-03-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多