MySQL加入三个不同的结果并计数

时间:2013-09-12 11:20:19

标签: mysql join sum

从三个不同的表中提取了三个结果。

每个表都是一个产品:loanscreditsdiscounts

贷款和信用获得了以下数据:clientidtypeproductiddate& expiration(将要去的日子)。 已获得折扣:clientiddateexpiration

结果是产品在10天(或更短)内到期并在两个日期之间注册的每个客户的次数(计数)。 示例(仅用于贷款):

SELECT clientid, COUNT(*)
FROM loans
WHERE ((type LIKE 'TITULAR') AND(date BETWEEN 'ccyy-mm-dd' AND 'ccyy-mm-dd') AND (expires <= 10))
GROUP BY clientid
ORDER BY clientid;

显然,并非所有客户同时获得贷款,信贷或折扣,但我需要得到一个结果,该结果总结了任何客户在限制日期内10天或更短时间内到期的任何产品的次数

所以,例如,如果客户#200获得3笔贷款,2个学分,只有一个折扣;所有这些都在date1和date2之间,到期时间等于或小于10;结果应该是6。

到目前为止,我已经尝试过:

SELECT loansr.clienteid, (loansr.count + creditsr.count + discountsr.count)
FROM
    (SELECT clienteid, COUNT(*) AS "count"
    FROM loans
    WHERE (type LIKE 'TITULAR') 
    AND (date BETWEEN '2009-08-01' AND '2009-10-30')
    AND (expires <= 10)
    GROUP BY clienteid) loansr,
    (SELECT clienteid, COUNT(*) AS "count"
    FROM credits
    WHERE (type LIKE 'TITULAR') 
    AND (date BETWEEN '2009-08-01' AND '2009-10-30')
    AND (expires <= 10)
    GROUP BY clienteid) creditsr,
    (SELECT clienteid, COUNT(*) AS "count"
    FROM discounts
    WHERE (date BETWEEN '2009-08-01' AND '2009-10-30')
    AND (expires <= 10)
    GROUP BY clienteid) discountsr
WHERE
    (loansr.clienteid = creditsr.clienteid = discountsr.clienteid)
ORDER BY loansr.clienteid;

编辑18:25 我认为如果我使用UNION ALL混合三个结果然后按clienteid分组我会得到我正在寻找的东西,不是吗?

SELECT clienteid AS "CLIENTE", SUM(COUNT) AS  "NUM_VECES_INCI_10_ACT_U3M" FROM
    ((SELECT clienteid, COUNT(*) AS "COUNT"
    FROM loans
    WHERE (titularidad_tipo LIKE 'TITULAR') 
    AND (date BETWEEN '2009-08-01' AND '2009-10-30')
    AND (expires >= 11)
    GROUP BY clienteid)
        UNION ALL
    (SELECT clienteid, COUNT(*) AS "COUNT"
    FROM credits
    WHERE (titularidad_tipo LIKE 'TITULAR') 
    AND (date BETWEEN '2009-08-01' AND '2009-10-30')
    AND (expires >= 11)
    GROUP BY clienteid)
        UNION ALL
    (SELECT clienteid, COUNT(*) AS "COUNT"
    FROM discounts
    WHERE (date BETWEEN '2009-08-01' AND '2009-10-30')
    AND (expires >= 11)
    GROUP BY clienteid)) orig
GROUP BY clienteid
ORDER BY clienteid;

1 个答案:

答案 0 :(得分:1)

如果可以,我会在评论中发布:) 如果使用UNION ALL,则应获得所需的结果。虽然确保为折扣表的贷款人,贷方和(日期,到期)表格提供适当的索引(我建议使用titularidad_tipo,date,expires)。如果你有适当的索引,你的结果会很快到来。