Question

I have 2 tables, one with a set of proposals and one with votes cast on the proposals, both joined with a unique ID.

The proposals table has a date field when the proposal was started, the votes have a date when the vote was cast. The proposal is marked as "success" when enough votes are cast. I want to find out how many days it takes in average to close votes.

My initial approach was to create a query that lists each proposal with the most recent vote through a left join:

SELECT proposals.pr_id, DATEDIFF(MAX(proposals_votes.`date`), proposals.`date`)
FROM proposals
LEFT JOIN proposals_votes ON proposals.pr_id = proposals_votes.pr_id
WHERE STATUS = 'success'

The issue is that this returns only one line, which is a surprise to me. I would have thought the MAX is done on the LEFT JOIN table and not on the resulting table.

Is there a way to do this within the LEFT JOIN or do I need to do a sub-query?

Was it helpful?

Solution

Use GROUP BY clause on pr_id to fetch no of days for each proposals

Try this:

SELECT p.pr_id, DATEDIFF(MAX(pv.`date`), p.`date`)
FROM proposals p 
LEFT JOIN proposals_votes pv ON p.pr_id = pv.pr_id
WHERE pv.status = 'success'
GROUP BY p.pr_id;

OTHER TIPS

If you want to multiple line you should use GROUP BY because of aggregate function always return only one rows. You will get multiple rows result by GROUP BY parameter like GROUP BY proposals.pr_id.

SELECT 
    proposals.pr_id,
    DATEDIFF(MAX(proposals_votes.date),proposals.date)
FROM
    proposals
        LEFT JOIN
    proposals_votes ON proposals.pr_id = proposals_votes.pr_id
WHERE
    STATUS = 'success'
GROUP BY proposals.pr_id;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top