2013-08-06 140 views
1

下面的SQL拋出錯誤8120,它說:Microsoft SQL Server錯誤

列「webgroup_message2_archive.opened」,因爲它不是在聚合函數或GROUP BY子句包含在選擇列表中無效

即使我沒有使用違規列作爲SELECT子句的一部分。當我將子查詢

SELECT webgroup_message2_testTable.message_id 

更改爲類似(111,222,...等)的列表`It works!所以問題來自與查詢集合函數不兼容的子查詢?我還確保子查詢的數據類型與測試表達式匹配。

SELECT 
    CASE 
     WHEN arch.opened = '1' 
     THEN(CASE 
      WHEN (message_id IN (SELECT webgroup_message2_testTable.message_id 
            FROM webgroup_message2_testTable)) 
      THEN 'Clicked' ELSE 'Opened' END) 
     ELSE 'No activity/response' 
    END AS status, count(1) 
FROM webgroup_message2_archive AS arch 
INNER JOIN webgroup_development AS dev 
     ON dev.development_id = arch.HTMLID 
WHERE dev.email_tracker_code = 'A4725' 
GROUP BY 
    CASE 
     WHEN arch.opened= '1' 
     THEN(CASE 
      WHEN (message_id IN (SELECT webgroup_message2_testTable.message_id 
            FROM webgroup_message2_testTable)) 
      THEN 'Clicked' ELSE 'Opened' END) 
     ELSE 'No activity/response' 
    END 
+0

'CASE WHEN arch.opened'是選擇列表的一部分.. – Blorgbeard

+0

嘗試在計數上放一些值.. say - > count(dev.development_id) – maSTAShuFu

回答

1

如果您嘗試按狀態計算消息數,則可以使用左連接並刪除子查詢。類似於戈登的答案,我打了幾分鐘,但外觀略有不同。這隻有在你的意圖是有效的。

SELECT 
    CASE 
     WHEN arch.opened = '1' 
     THEN (CASE WHEN test.message_id IS NOT NULL THEN 'Clicked' ELSE 'Opened' END) 
     ELSE 'No activity/response' 
    END AS status, 
    count(distinct(arch.message_id)) 
FROM webgroup_message2_archive AS arch 
INNER JOIN webgroup_development AS dev 
     ON dev.development_id = arch.HTMLID 
LEFT JOIN webgroup_message2_testTable AS test 
     ON arch.message_id = test.message_id 
WHERE dev.email_tracker_code = 'A4725' 
GROUP BY 
    CASE 
     WHEN arch.opened = '1' 
     THEN (CASE WHEN test.message_id IS NOT NULL THEN 'Clicked' ELSE 'Opened' END) 
     ELSE 'No activity/response' 
    END 
  • 不知道arch.message_id是正確的,或者如果它應該dev.message_id。您應該總是嘗試在列名前面添加表/別名,以便對列的來源沒有任何疑問。
2

我不認爲你可以在group by子句中使用子查詢。您可以使用left join來查看消息是否可用,從而做同樣的事情。

SELECT (CASE WHEN arch.opened= '1' 
      THEN (CASE WHEN ttmessage_id is not null 
         THEN 'Clicked' 
         ELSE 'Opened' 
        END) 
      ELSE 'No activity/response' 
     END), count(1) 
FROM webgroup_message2_archive arch INNER JOIN 
    webgroup_development AS dev 
    ON dev.development_id = arch.HTMLID left outer join 
    (select distinct tt.message_id as ttmessage_id 
     from webgroup_message2_testTable tt 
    ) tt 
    on message_id = tt.ttmessage_id 
WHERE dev.email_tracker_code = 'A4725' 
GROUP BY (CASE WHEN arch.opened= '1' 
       THEN (CASE WHEN ttmessage_id is not null 
          THEN 'Clicked' 
          ELSE 'Opened' 
        END) 
       ELSE 'No activity/response' 
      END)