我的询问:
SELECT AgeBand, COUNT(LoanID) as "Number of loans"
FROM (
SELECT CASE
WHEN (Client.Age>Age.Low_Value and Client.Age<=Age.High_Value) THEN AgeID
END as AgeBand,
LoanID
FROM Loan, Client, Age
WHERE Loan.CustomerID = Client.CustomerID
AND Loan.PastDue_Days >= 1
GROUP BY Age)
GROUP BY AgeBand
这是行不通的。年龄表:
年龄ID | 低值 | 高价值 |
---|---|---|
A | 0 | 10 |
B | 10 | 20 |
C | 20 | 30 |
D | 30 | 40 |
E | 40 | 50 |
F | 50 | 60 |
G | 60 | 70 |
H | 70 | 80 |
我 | 80 | 90 |
J | 90 | 100 |
K | 100 | 150 |
如何使用年龄表来引用这些年龄范围,而不必对它们进行硬编码?
上面的查询返回空白行的计数和 AgeBand 的“A”。期望的结果是根据年龄范围值计算每个年龄范围之间的贷款计数。
你需要这样的东西:
SELECT AgeID AS AgeBand, COUNT(LoanID) AS "Number of loans"
FROM Age
LEFT JOIN Client
ON (Client.Age>Age.Low_Value and Client.Age<=Age.High_Value)
LEFT JOIN Loan
ON Client.CustomerID = Loan.CustomerID AND Loan.PastDue_Days >= 1
GROUP BY `AgeID`
说明:
Age
table
作为出发点,目的是让每个 Age
LEFT JOIN Client
,所以我们打算找到所有该年龄的客户(如果存在的话)Client
的连接标准是 Client.Age
符合 Age
LEFT JOIN
与 Loan
,这样我们就可以了解 Age
CustomerID
与已找到的 Client
的对应项匹配,并且 PastDue_Days
严格为正GROUP BY AgeID
确保我们正确聚合,每个Age
AgeID AS AgeBand
,并且我们打算将 COUNT(LoanID)
作为贷款数量,但是,如果某些 Age
组没有 Loan
匹配