0

请帮助我如何解决此问题

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

这是我的查询

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

2 回答 2

6

在子查询中删除此列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
于 2012-12-29T09:39:29.580 回答
1

在 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
于 2012-12-29T10:16:22.357 回答