1

下面的 SQL 抛出错误 8120,它说:

列 'webgroup_message2_archive.opened' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中

即使我没有使用违规列作为SELECT子句的一部分。当我更改子查询时

SELECT webgroup_message2_testTable.message_id

到(111,222,...等)之类的列表`它有效!那么问题来自与聚合函数不兼容的子查询?我还确保子查询的数据类型与测试表达式匹配。

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 
4

2 回答 2

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)
于 2013-08-06T01:29:06.533 回答
1

如果您尝试按状态获取消息计数,那么您可以使用左连接并摆脱子查询。类似于 Gordon 的回答,它比我快了几分钟,但在外观上略有不同。仅当这是您的意图时才有效。

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。您应该始终尝试使用表/别名作为列名的前缀,这样就不会对列的来源有任何疑问。
于 2013-08-06T01:47:37.367 回答