2012-12-29 54 views
0

請幫助我如何修復了這個問題SQL:消息116,級別16,狀態1,第1行只有一個表達式可以在選擇列表中指定當子查詢未與EXISTS引入

消息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) 
     ) 

回答

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

+1 CTE FTW,強大的功能,往往使查詢更容易閱讀。 – booyaa

+0

@booyaa你絕對正確它powerfuuuuuuuuuuul;)) –

相關問題