【问题标题】:SQL: Msg 116, Level 16, State 1, Line 1 Only one expression can be specified in the select list when the subquery is not introduced with EXISTSSQL: Msg 116, Level 16, State 1, Line 1 不带EXISTS引入子查询时,选择列表中只能指定一个表达式
【发布时间】:2012-12-29 09:38:44
【问题描述】:

请帮我解决这个问题

消息 116,第 16 级,状态 1,第 1 行
不引入子查询时,选择列表中只能指定一个表达式 存在。

这是我的查询

SELECT  a.RegId,
        a.PropertyThumbnail
FROM    tblPropertyDetail a
WHERE   a.RegId NOT IN 
        (
            SELECT  RegId,
                    COUNT(RegId) AS NumOccurrences
            FROM tblPropertyDetail
            GROUP BY RegId
            HAVING (COUNT(RegId) > 1)
        )

【问题讨论】:

    标签: sql-server tsql select


    【解决方案1】:

    删除子查询COUNT(RegId) AS NumOccurrences中的这一列

    SELECT a.RegId,
            a.PropertyThumbnail
    FROM tblPropertyDetail a
    WHERE a.RegId NOT IN (
                    SELECT RegId
                    FROM tblPropertyDetail
                    GROUP BY RegId
                    HAVING (COUNT(RegId) > 1)
                    )
    

    使用NOT IN时,预计子查询返回的列数只有一。

    或者,您也可以使用JOIN 执行此操作

    SELECT  a.RegId,
            a.PropertyThumbnail
    FROM    tblPropertyDetail a
            LEFT JOIN
            (
                SELECT RegId, COUNT(RegId) AS NumOccurrences
                FROM tblPropertyDetail
                GROUP BY RegId
                HAVING (COUNT(RegId) > 1)
            ) b ON a.RegId = b.RegId
    WHERE   b.RegId IS NULL
    

    【讨论】:

      【解决方案2】:

      在 SQLServer2005+ 中使用 CTE 和聚合窗口函数

      ;WITH cte AS
       (
        SELECT RegId, PropertyThumbnail, COUNT(*) OVER (PARTITION BY RegId) AS cnt
        FROM tblPropertyDetail
        )
        SELECT RegId, PropertyThumbnail
        FROM cte
        WHERE cnt <= 1
      

      【讨论】:

      • +1 CTE FTW,强大的功能通常使查询更易于阅读。
      猜你喜欢
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 2011-09-24
      • 2018-04-14
      相关资源
      最近更新 更多