サブクエリでメイン クエリと同じテーブルから複数の列のカウントを取得するクエリで問題が発生しています。
これが私のクエリです:
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
サブクエリの 1 つに基づいて基本的なクエリを作成すると、正しいカウントが得られますが、そのままではカウントが大幅に膨らんでしまいます。
私は何を間違っていますか?