我遇到了一个查询问题,我想从子查询中的同一个表中检索多个列的计数作为主查询。
这是我的查询:
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
如果我基于其中一个子查询创建一个基本查询,我会得到正确的计数,但实际上我会得到大量夸大的计数。
我究竟做错了什么?