从三个不同的表中提取了三个结果。
每个表都是一个产品loans
:credits
和discounts
。
贷款和信贷得到以下数据:clientid
, type
, productid
, date
& expiration
(剩余天数)。折扣获得clientid
:date
和expiration
。
结果是每个客户的产品在 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 笔信贷和 1 次折扣;所有这些都在 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;