SQL计算一个表相对于另一个表的行

时间:2017-06-05 23:05:28

标签: mysql sql

我有3个不同的表:

客户端

+----+-----------+----------+
| id | firstName | lastName |
+----+-----------+----------+
|  1 | John      | Doe      |
|  2 | Jane      | Doe      |
+----+-----------+----------+

贷款

+----+--------+-----------+----------------+
| id | amount | client_id | institution_id |
+----+--------+-----------+----------------+
|  1 |    200 |         2 |              3 |
|  2 |    400 |         1 |              1 |
+----+--------+-----------+----------------+

机构

+----+---------------+
| id |     name      |
+----+---------------+
|  1 | Institution A |
|  2 | Institution B |
|  3 | Institution C |
+----+---------------+

我希望创建一个客户与每个机构(对于机构表中的每一行)的贷款数量列表。包括当客户向机构提供0贷款时。

看起来像:

+-----------+-----------+----------+--------------------------+-----------+
| client_id | firstName | lastName | financialInstitutionName | loanCount |
+-----------+-----------+----------+--------------------------+-----------+
|         1 | John      | Doe      | Institution A            |         1 |
|         1 | John      | Doe      | Institution B            |         0 |
|         1 | John      | Doe      | Institution C            |         0 |
|         2 | Jane      | Doe      | Institution A            |         0 |
|         2 | Jane      | Doe      | Institution B            |         0 |
|         2 | Jane      | Doe      | Institution C            |         1 |
+-----------+-----------+----------+--------------------------+-----------+

我尝试了所有连接,子查询和where子句的方式,但没有成功。我没有掌握的概念是每个机构,每个客户(总计数机构x客户)如何获得一排。如果没有子查询或联合连接可以进行查询,我会很高兴。

感谢您的时间!

2 个答案:

答案 0 :(得分:0)

SELECT 
    loan.client_id, 
    client.firstName, 
    client.lastName, 
    institution.name as financialInstitutionName, 
    COUNT(loan.id) as loanCount 
FROM client 
INNER JOIN loan ON client.id = loan.client_id 
INNER JOIN institution ON loan.institution_id = institution.id 
GROUP BY client.id;

答案 1 :(得分:0)

FROM设置中的第一个子查询数据,因此每个客户都有每个机构的记录。然后将其加入一个计算贷款数量的子查询。

SELECT 
    d.client_id,
    d.firstName,
    d.lastName,
    d.name AS financialInstitutionName,
    CASE WHEN l IS NULL
        THEN 0
        ELSE l.loanCount
    END AS loanCount

FROM
(
    SELECT
        Client.id AS client_id,
        Client.firstName,
        Client.lastName,
        Institution.id AS institution_id,
        Institution.name
    FROM Client, Institution
) AS d

LEFT JOIN (
    SELECT client_id, institution_id, COUNT(id) AS loanCount 
    FROM Loan
    GROUP BY client_id, institution_id
) AS l ON d.client_id = l.client_id AND d.institution_id = l.institution_id

编辑:包含每个机构的记录

编辑:拼写