首页 > 解决方案 > 如何使用 2 个表创建具有 2 个计数的组?

问题描述

如果我能在这里得到一些建议,那就太好了。我正在尝试使用来自 2 个表的信息创建具有 2 个不同计数的 GROUP BY。我设法创建了一个 GROUP BY,它只有我想要的两个计数之一,但被困在那里。帮助表示赞赏!

Table_1 
ID | Date     | Error_code 
101| 01/11/19 | A 
102| 01/11/19 | B 
103| 02/11/19 | A 
104| 03/11/19 | A 

Table_2 
ID | Status_code 
101| 1 
102| 2 
103| 1 
104| 1 

最终我试图达到这个特定的结果:

date     | error_code | count_status_code_1 | count_status_code_2 
01/11/19 | A          | 1                   | 1 
02/11/19 | A          | 0                   | 0 
03/11/19 | A          | 1                   | 0 

这是我到目前为止得到的:

SELECT date, 
       error_code, 
       Count(*) AS count_status_code_1 
FROM   table_1 
       JOIN table_2 
         ON table_1.id = table_2.id 
WHERE  error_code = 'A' 
       AND status_code = 1 
GROUP  BY date, 
          error_code 
ORDER  BY date ASC;

我应该如何修改代码以添加第二个计数列?

提前致谢!

标签: mysqlsqlpostgresql

解决方案


使用条件聚合:

select date, error_code, 
       sum(case when Status_code =1 then 1 else 0 end) as count_status_code_1,
       sum(case when Status_code =2 then 1 else 0 end) as count_status_code_2
  from table_1 t1
  join table_2 t2
    on t1.id = t2.id
 where error_code = 'A' 
 group by date, error_code
 order by date;

推荐阅读