sql从2个表中计算总数

gev0vcfq  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(340)

我有两个表银行和申请人,如何查询显示所有银行并统计使用该银行的申请人数量
[银行][1]:

| id | Bank_desc    
|----|---------
| 1  | Ambank  
| 2  | Maybank  
| 3  | RHB BANK 
| 4  | OSBC

【申请人】【2】:

| id | Name | Bank|
|----|------|----|
|  1 | JACK |  3 |
|  2 | ANDY |  1 |
|  3 | VOID |  1 |

我想展示这样的东西,[结果][2]:

| id | Bank     |Total|
|----|----------|----|
|  1 | Ambank   |  2 |
| 2  | Maybank  |  0 |
| 3  | RHB BANK |  1 |
| 4  | OSBC     |  0 |

我试过这个

SELECT b.Bank_desc, Count(a.id),
FROM applicant a
LEFT JOIN bank b on b.id= a.bank
GROUP BY b.bank

但结果表明只有银行才有价值
[结果][2]:

| id | Bank     |Total|
|----|----------|----|
|  1 | Ambank   |  2 |
| 2  | RHB BANK |  1 |

任何帮助都将不胜感激,提前谢谢!

7gcisfzg

7gcisfzg1#

如果颠倒表的顺序,则当前查询将起作用:

SELECT
    b.id,
    b.Bank,
    COUNT(a.Bank) AS Total
FROM Bank b
LEFT JOIN Applicant a
    ON b.id = a.Bank
GROUP BY
    b.id,
    b.Bank;

演示

mwg9r5ms

mwg9r5ms2#

选择bank\u name,count(u.bank\u id)from bank b left join users u on b.id=u.bank\u id group by u.bank\u id

相关问题