sql使用count和where显示所有数据

ngynwnxp  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(451)

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

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

【申请人】【2】:

| id | Name | Bank|STEP|
|----|------|----|----|
|  1 | JACK |  3 | W1 |
|  2 | ANDY |  1 | W4 |
|  3 | VOID |  1 | W1 |
|  4 | RAY  |  1 | W5 |

我想显示所有银行名单和申请人的总数,但只在申请人在步骤w1或w4,[结果][2]:

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

我试过这个

SELECT
 b.id,
 b.Bank, COUNT(a.Bank) AS Total FROM Bank b LEFT JOIN Applicant a ON b.id = a.Bank WHERE a.step ='W1' or a.step='W4 GROUP BY b.id, b.Bank;

但结果表明,只有银行有价值,而不是所有的银行
[结果][2]:

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

如果我删除其中a.step='w1'或a.step='w4'
它将显示所有的银行名单,但也显示从所有步骤
任何帮助都将不胜感激,提前谢谢!
演示sql

lpwwtiir

lpwwtiir1#

你的问题是 WHERE 该条款不包括任何在这两个步骤中都没有客户的银行。您需要将查询更改为使用条件聚合:

WITH Bank AS (
    SELECT 1 AS id, 'Ambank' AS Bank UNION ALL
    SELECT 2, 'Maybank'  UNION ALL
    SELECT 3, 'RHB BANK' UNION ALL
    SELECT 4, 'OSBC'
),
Applicant AS (
    SELECT 1 AS id, 'JACK' AS Name, 3 AS Bank, 'W1' AS Step UNION ALL
    SELECT 2, 'ANDY', 1,'W1' UNION ALL
     SELECT 3, 'ROY', 1,'W4' UNION ALL
    SELECT 4, 'VOID', 1,'W5'
)

SELECT
    b.id,
    b.Bank,
    SUM(CASE WHEN a.step = 'W1' OR a.step = 'W4' THEN 1 ELSE 0 END) AS Total
FROM Bank b
LEFT JOIN Applicant a
    ON b.id = a.Bank
GROUP BY
    b.id,
    b.Bank
ORDER BY
    b.id;

输出:

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

更新的dbfiddle

相关问题