0

我遇到了一个查询问题,我想从子查询中的同一个表中检索多个列的计数作为主查询。

这是我的查询:

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

如果我基于其中一个子查询创建一个基本查询,我会得到正确的计数,但实际上我会得到大量夸大的计数。

我究竟做错了什么?

4

1 回答 1

0

我不知道为什么您的查询是错误的,但我知道您应该如何编写它。所有这些子计数都是杀手,尝试理解这个技巧,你会在可读性和性能方面获得很多:

SELECT
    CM.entityId,
    SUM(invoiceAge < 14) as under14,
    SUM(invoiceAge >= 14 AND invoiceAge < 30) as under14to30,
    SUM(invoiceAge >= 30 AND invoiceAge < 60) as under30to60,
    SUM(invoiceAge >= 60 AND invoiceAge < 90) as under60to90,
    SUM(invoiceAge > 90) 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;

顺便说一句,invoiceAge = 90这里不适合任何类别。

于 2012-08-08T07:10:51.053 回答