Question

Here are the two tables and the only columns that matter for this question.

Mailing M
m_id: Id for each of three mailing type

Mailing Received MR
u_id: Id for person who received mailing m_id: FK

I have successfully created this query

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

which returns a table that looks like this

Mailing Type     Mailings Received
1                500
2                350
3                600

Which is fantastic. Really. But I am trying to return a third column that tells the percentage of the mailings received by mailing type and that is not going as smoothly. Here is what I have tried in a sub query thus far:

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;

No dice.

EDIT: u_id is sorted into three rows through the COUNT and GROUP BY functions. I have no idea how to create a column of percentages when return rows are divided as such.

Was it helpful?

Solution

This should work:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top