我正在尝试从多个表中返回多个计数。以下是我必须从同一个表中返回多个计数的内容(非常感谢此处的帮助):
SELECT
m.mailing_name AS Mailing_Name,
COUNT(mr.mailing_recipient_id) AS Total_Recipients
FROM mailing_recipient mr
INNER JOIN mailing m
ON mr.mailing_id = m.mailing_id
GROUP BY m.mailing_name
ORDER BY m.mailing_name;
这将返回每种电子邮件类型的收件人数。我希望创建一个脚本,同时返回上述内容以及每个电子邮件类型的电子邮件打开总数和每个收件人打开的电子邮件数。
附加表是mailing_recipient_open,其中mailing_recipient_open_id充当open / clicks和mailing_recipient_open_type_id的标识符,告知每条记录是打开还是单击(1 =单击,2 =打开)。 mailing_recipient_id充当表之间的外键。
这是我能够得到的最接近的。我非常喜欢上述格式,因为它更干净,但我不知道我是否能按照描述加入。
SELECT
mailing_name,
mr.mailing_recipient_id,
mailing_recipient_open_id,
COUNT( mr.mailing_recipient_id ) AS Total_recipient,
mailing_recipient_open_id AS open_click
FROM mailing m
LEFT OUTER JOIN mailing_recipient mr ON m.mailing_id = mr.mailing_id
LEFT OUTER JOIN mailing_recipient_open mc ON mr.mailing_recipient_id = mc.mailing_recipient_id
GROUP BY mailing_name;
我的输出如下:
mailing_name mailing_recipient_id mailing_recipient_open_id Total_recipient Open_click
Mailing A 1 NULL 203234 NULL
Mailing B 22342 12342 123948 8738
Mailing C 12322 NULL 145203 NULL
这根本不对。
感谢。
答案 0 :(得分:0)
我不太确定我是否理解您在第二个查询中想要计算的内容,但您应该能够适应这一点。我们的想法是创建几个表(子查询),其中包含mailing_name作为键以及您想要的任何计数/聚合值...并将它们全部连接在该mailing_name键上
select a.mailing_name, a.totalrecipients, b.counter
from
(SELECT
m.mailing_name AS Mailing_Name,
COUNT(mr.mailing_recipient_id) AS Total_Recipients
FROM mailing_recipient mr
INNER JOIN mailing m
ON mr.mailing_id = m.mailing_id
GROUP BY m.mailing_name
)a
left join
(select mailing_name, count(*) as counter
from tableforcounting
group by mailing_name)b
on a.mailing_name = b.mailing_name
ORDER BY m.mailing_name
你可以继续将这些链接在一起以获得尽可能多的其他计数,只要它们被相同的mailing_name键分组即可。如果您希望常规字段(如mailing_name_id或sort)加入到邮件名称表中并获取所需字段。
希望这是有道理的,我可以澄清你是否需要;)
添加:
此查询的更通用结构......
select a.groupingname, a.count, b.count, c.count, etc...
from
(select groupingname, count(1) as count from table t group by groupingname) a
left join
(select groupingname, count(1) as count from differnt_table t where open = 1 group by groupingname) b
on a.groupingname = b.groupingname
left join
(select grouping name, count(1) as count from 3rdtable t) c
on a.groupingname = c.groupingname
查看它是如何进行的一系列子查询,每个子查询都返回一个加入键加上一个计数值...然后select语句只从一个表中获取键,然后从子查询中获取其余的计数值?