SELECT a.lead_id, c.state_name AS COL1DATA, count( c.state_name ) AS leadcount, (
SELECT count( won_loss ) AS wonlosscount
FROM lead_status
WHERE (won_loss = 'loss')
AND lead_id = a.lead_id
) AS losscount
FROM lead AS a
JOIN states AS c ON a.state_id = c.states_id
GROUP BY c.state_name
ORDER BY losscount DESC
the answer i get is
lead_id COL1DATA leadcount losscount 1 Queensland 7 0 8 Victoria 3 0
lead status
lead_id won_loss won_price won_mainreason loss_mainreason loss_attachment_id lost_dont_sell_note add_note dealer_satisfaction
5 win 4655 pricing fghfg somewhat
8 won 34543 pricing sfdgs satisfied
7 loss service Additional Notes verygood
9 loss not_in_stock Additi satisfied
but the loss count should be 1 and 1
any help is appricated
I’m guessing that there’s a problem with mixing the non-aggregated lead_id in the correlated query all the while grouping on state_name. Perhaps you can describe what you’re looking to get back.
EDIT: Based on OP feedback in comment below.
EDIT 2: Changed to left outer joins based on chat session. Not all leads have a lead_status.
I might argue that this version is slightly better. But I didn’t want to totally change your query. (I did change the aliases because A and C were confusing.)
The lead_id column you have included in the output is unpredictable unless the group only has one row. Based on what you’ve said, I doubt that you really want it.