合并两个select语句

时间:2014-07-24 10:07:44

标签: mysql sql

我需要合并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

以便输出如下所示:

count(opens)|count(sends)|Week
 2               8        52
 5              15        53

我尝试过各种各样的选择,但是计数的结果总是累积到一个总数而且没有按周计算。

任何想法?

3 个答案:

答案 0 :(得分:1)

只需添加额外的计数,但使用IF和SUM: -

SELECT SUM(IF(emaildata2.EM_SENT_FLAG='Yes', 1, 0), SUM(IF(emaildata2.EM_OPEN_FLAG, 1, 0)), emaildata2.EMAIL_FINANCIAL_WEEK 
FROM `email-redeye`.emaildata2
GROUP BY emaildata2.EMAIL_FINANCIAL_WEEK

答案 1 :(得分:0)

您可以使用 SUM WITH 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 WITH IF ,如下所示:

语法

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

答案 2 :(得分:0)

通过手机拨号,这是一个非常简短的回答。

让您的第二个查询成为您的第一个查询。

如果您不熟悉子查询,它基本上是一个完整的查询来代替表名。它们非常有用。