不一定是高性能代码:
SELECT m, y, sent_count, open_count, clicked_count
FROM
(SELECT MONTH(sent_on) as m, YEAR(sent_on) as y
FROM my_table
WHERE sent = true
GROUP BY MONTH(sent_on), YEAR(sent_on)
UNION ALL
SELECT MONTH(open), YEAR(open)
FROM my_table
WHERE sent = true
GROUP BY MONTH(open), YEAR(open)
UNION ALL
SELECT MONTH(open), YEAR(open)
FROM my_table
WHERE sent = true
GROUP BY MONTH(open), YEAR(open)) d
LEFT JOIN
(Select MONTH(sent_on) as m , YEAR(sent_on) as y, count(sent_on) sent_count
FROM my_table
WHERE sent = true
GROUP BY MONTH(sent_on), YEAR(sent_on)) s on (s.y=d.y and s.m=d.m)
LEFT JOIN
(Select MONTH(open) as m , YEAR(open) as y, count(open) open_count
FROM my_table
WHERE sent = true
GROUP BY MONTH(open), YEAR(open)) o on (o.y=d.y and o.m=d.m)
LEFT JOIN
(Select MONTH(clicked) as m , YEAR(clicked) as y, count(clicked) clicked_count
FROM my_table
WHERE sent = true
GROUP BY MONTH(clicked), YEAR(clicked)) c on (c.y=d.y and c.m=d.m);
假定打开并单击已发送。
更新:为了性能,我们可以从以下查询开始:
Select MONTH(sent_on) sm, YEAR(sent_on) sy,
MONTH(OPEN) om, YEAR(OPEN) oy,
MONTH(clicked) cm, YEAR(clicked) cy,
count(sent_on) sent_cnt, count(clicked) clicked_cnt, count(open) open_cnt
FROM my_table
WHERE sent = true
GROUP BY MONTH(sent_on), YEAR(sent_on),
MONTH(OPEN), YEAR(OPEN),
MONTH(clicked), YEAR(clicked);