以下是两个表格和唯一对此问题重要的列。
邮寄M
m_id:三种邮件类型
邮寄收到的MR
u_id:收到邮件的人的ID
m_id:FK
我已成功创建此查询
SELECT
m.m_id AS 'Mailing Type',
COUNT(mr.u_id) AS 'Mailings Received'
FROM mailing m
Left join
mailing_received mr
ON mr.m_id = m.m_id
GROUP BY m.m_id
返回一个看起来像这样的表
Mailing Type Mailings Received
1 500
2 350
3 600
哪个太棒了。真。但我试图返回第三列,告诉邮件类型收到的邮件的百分比,并不是那么顺利。以下是我到目前为止在子查询中尝试过的内容:
SELECT
m.m_id,
u_id * 100/ (SELECT COUNT(*) FROM mailing_received) AS "PERC REC"
FROM mailing m
LEFT JOIN
mailing_received mr
ON
m.m_id = mr.m_id
GROUP BY m.m_id;
没有骰子。
编辑:u_id
通过COUNT和GROUP BY函数分为三行。当返回行被分割时,我不知道如何创建一列百分比。
答案 0 :(得分:1)
这应该有效:
SELECT
m.m_id AS "Mailing Type",
COUNT(mr.u_id) AS "Mailings Received",
COUNT(mr.u_id) / (SELECT COUNT(*) FROM mailing_received) AS "PERC REC"
FROM mailing m
Left join mailing_received mr
ON mr.m_id = m.m_id
GROUP BY m.m_id