簡體   English   中英

在不同表上使用SUM和COUNT進行SQL聚合選擇

[英]SQL aggregation select using SUM and COUNT on different tables

我有一張桌子的電子郵件

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

table2是響應

email_id email  response
1   xyz@email.com   xxxx
1   xyzw@email.com  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嗎?

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

在將它們連接在一起之前,需要分別匯總發送和響應。 加入日期是日期,該日期必然來自“已發送”信息:

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`;

您的回復與“已發送”信息甚至日期都沒有鏈接的明顯事實表明您的操作和數據確實存在問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM