I am having trouble with a query that I want to retrieve counts for multiple columns from the same table in the subqueries as the main query.
Here is my query:
SELECT
CM.entityId,
(SELECT COUNT(*)
FROM _credit_control_main
WHERE invoiceAge < 14 AND entityId = CM.entityId) AS under14,
(SELECT COUNT(*)
FROM _credit_control_main
WHERE invoiceAge >= 14 AND invoiceAge < 30 AND entityId = CM.entityId) AS under14to30,
(SELECT COUNT(*)
FROM _credit_control_main
WHERE invoiceAge >= 30 AND invoiceAge < 60 AND entityId = CM.entityId) AS under30to60,
(SELECT COUNT(*)
FROM _credit_control_main
WHERE invoiceAge >= 60 AND invoiceAge < 90 AND entityId = CM.entityId) AS under60to90,
(SELECT COUNT(*)
FROM _credit_control_main
WHERE invoiceAge > 90 AND entityId = CM.entityId) AS over90,
COUNT(*) AS iCount
FROM
_credit_control_main AS CM
WHERE
((CM.invoiceNet + CM.invoiceVat) - (creditNet+creditVat)) - (CM.paymentTotal - (CM.creditNet + CM.creditVat)) > 0.00
GROUP BY
entityId
ORDER BY
`CM`.`entityId` ASC
If I create a basic query based on one of the subqueries I get the correct count, but as it is I get vastly inflated counts.
What am I doing wrong?
I don’t know why your query is wrong but I know how you should write it instead. All these subcount are killers, try understanding this trick and you’ll gain a lot in readability and performance:
And by the way, the
invoiceAge = 90fits in no category here.