我需要合并2个选择结果,其中一个是这样的:

SELECT count(emaildata2.EM_SENT_FLAG), emaildata2.EMAIL_FINANCIAL_WEEK
FROM `email-redeye`.emaildata2
WHERE emaildata2.EM_SENT_FLAG='Yes'
GROUP BY emaildata2.EMAIL_FINANCIAL_WEEK

另一个是这样的:
SELECT count(emaildata2.EM_OPEN_FLAG), emaildata2.EMAIL_FINANCIAL_WEEK
FROM `email-redeye`.emaildata2
WHERE emaildata2.EM_OPEN_FLAG='Yes'
GROUP BY emaildata2.EMAIL_FINANCIAL_WEEK

输出如下:
计数(打开)|计数(发送)|周
2 8 52个
5 15 53个
我试过各种各样的选择,工会,但统计的结果总是汇总到一个总数,并不是按周分解的。
有什么想法吗?

最佳答案

可以将SUM与CASE一起使用,如下所示:
语法:
CASE WHEN CONDITION THEN TRUE_VALUE ELSE FALSE_VALUE END

SELECT
 SUM(CASE WHEN emaildata2.EM_SENT_FLAG = 'Yes' THEN 1 ELSE 0 END) SEND_COUNT,
 SUM(CASE WHEN emaildata2.EM_OPEN_FLAG= 'Yes' THEN 1 ELSE 0 END) OPEN_COUNT,
 emaildata2.EMAIL_FINANCIAL_WEEK
FROM `email-redeye`.emaildata2
GROUP BY emaildata2.EMAIL_FINANCIAL_WEEK

您也可以将SUM与以下情况一起使用:
语法:
IF(CONDITION) , TRUE_VALUE , FALSE_VALUE
SELECT
  SUM(IF(emaildata2.EM_SENT_FLAG='Yes', 1, 0) SEND_COUNT,
  SUM(IF(emaildata2.EM_OPEN_FLAG='Yes', 1, 0)) OPEN_COUNT,
  emaildata2.EMAIL_FINANCIAL_WEEK
FROM `email-redeye`.emaildata2
GROUP BY emaildata2.EMAIL_FINANCIAL_WEEK

09-20 14:52