2013-09-10 54 views
1

我有一個表電子郵件SQL聚合選擇使用SUM和COUNT在不同的表

id date sent_to 
1 2013-01-01 345 
2 2013-01-05 990 
3 2013-02-05 1000 

表2是響應

email_id email response 
1 [email protected] xxxx 
1 [email protected] yyyy 
. 
. 
. 

我想用下面的格式結果:

Month total_number_of_subscribers_sent total_responded 
2013-01 1335 2 
. 
. 

這是我的查詢:

SELECT 
DATE_FORMAT(e.date, '%Y-%m')AS `Month`, 
    count(*) AS total_responded, 
SUM(e.sent_to) AS total_sent 
FROM 
    responses r 
LEFT JOIN emails e ON e.id = r.email_id 
WHERE 
e.date > '2012-12-31' AND e.date < '2013-10-01' 
GROUP BY 
    DATE_FORMAT(e.date, '%Y %m') 

它可以與total_responded配合使用,但total_sent以百萬爲單位瘋了,顯然是因爲生成的連接表具有冗餘值。

所以,基本上我可以做一個SUM和COUNT在單獨的表上相同的查詢?

+0

由於您的「表格」示例沒有顯示blastid列如何將它們連接在一起,因此無法確定您想要獲取的內容。 –

+0

我編輯過它 – user2766524

回答

0

如果要計算每個表中的重複項,則查詢有點複雜。

在將它們連接在一起之前,您需要分別彙總發送和響應。連接是的日期,這必然來自於「已發送」的信息:

select r.`Month`, coalesce(total_sent, 0) as total_sent, coalesce(total_emails, 0) as total_emails, 
     coalesce(total_responses, 0) as total_responses, 
     coalesce(total_email_responses, 0) as total_email_responses 
from (select DATE_FORMAT(e.date, '%Y-%m') as `Month`, 
      count(*) as total_sent, count(distinct email) as total_emails 
     from emails e 
     where e.date > '2012-12-31' AND e.date < '2013-10-01' 
     group by DATE_FORMAT(r.date, '%Y-%m') 
    ) e left outer join 
    (select DATE_FORMAT(e.date, '%Y-%m') as `Month`, 
      count(*) as total_responses, count(distinct r.email) as total_email_responses 
     from emails e join 
      responses r 
      on e.email = r.email 
     where e.date > '2012-12-31' AND e.date < '2013-10-01' 
    ) r 
    on e.`Month` = r.`Month`; 

的明顯事實,你的響應沒有鏈接到「已發送」的信息 - 甚至沒有日期 - 提出一個真正的您的操作和數據有問題。