mysql - 如何使用 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;
我应该如何修改代码以添加第二个计数列?
提前致谢!
解决方案
使用条件聚合:
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;
推荐阅读
- mobx - 我可以访问 observable 中键的父/兄弟吗?
- selenium - 使用 Selenium Web 驱动程序在多个窗口或实例上执行
- anchor - HTMLPurifier 移除- 如何阻止这种情况发生?
- c++ - 内存查看器,填充值
- scala - 如何验证 scala 语法?
- python - 如何将 Python 数字列表转换为 json 对象
- android - Android 在 lambda 函数中获取资源 ID 返回错误的 ID
- python - Conda: concurrent.futures.process.BrokenProcessPool: 进程池中的一个进程在未来运行或挂起时突然终止
- python-3.x - TensorFlow Estimator 以 Web 格式保存 (tfjs)
- javascript - 使用数组列表并在 React 中访问其元素