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

时间:2018-10-01 02:05:36

标签: mysql select count where-clause mysql-error-1064

我有2个表Bank and Applicant,如何查询显示所有银行并计算使用该银行的申请人数量

Bank

| 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 |

我尝试过此sql

 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

它会显示所有银行清单,而且还会显示所有步骤

任何帮助将不胜感激,在此先感谢!

DEMO SQL

1 个答案:

答案 0 :(得分:0)

您的问题是您的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

输出:

while (startIndex := find(target, key, startIndex)) != -1:
    matchesFound += 1
    startIndex + 1
    return matchesFound

Updated DBFiddle