mysql - Mysql将计数查询从多列组合成单列
问题描述
我有一个表格“详细信息”,如下所示
| ID | NAME | PARTS | SERVICE | LOCATION | TIME |
|----|--------|-------|---------|----------|---------------|
| 1 | John | 5 | Repair | A | 1597893635294 |
| 2 | Smith | 1 | Install | A | 1597893635294 |
| 3 | Will | 1 | Repair | B | 1597893635294 |
| 4 | Jade | 10 | Install | A | 1597893635294 |
| 5 | George | 2 | Install | B | 1597893635294 |
| 6 | Ray | 4 | Repair | A | 1597893635294 |
我需要基于服务和位置排序的总行数
Select SERVICE,LOCATION,count(*) as TOTAL from Details group by SERVICE,LOCATION order by SERVICE desc;
结果为
| SERVICE | LOCATION | TOTAL |
|---------|----------|-------|
| Repair | A | 2 |
| Repair | B | 1 |
| Install | A | 2 |
| Install | B | 1 |
我需要结果
| SERVICE | A | B | TOTAL |
|---------|---|---|-------|
| Repair | 2 | 1 | 3 |
| Install | 2 | 1 | 3 |
解决方案
您可以尝试以下使用conditional aggregation
Select SERVICE,
count(case when location='A' then 1 end) as A,
count(case when location='B' then 1 end) as B,
count(*) as TOTAL
from Details group by SERVICE
order by SERVICE desc
推荐阅读
- php - 将自定义字段添加到 WooCommerce 新帐户页面
- python - 使用烧瓶创建数据库,既没有设置 SQLALCHEMY_DATABASE_URI 也没有设置 SQLALCHEMY_BINDS
- spring - Spring批量限制作业执行
- c# - 绑定延迟后以编程方式触发事件
- kubernetes - 创建指向两个服务的 Kubernetes 入口
- laravel - 按月查询的 Laravel Group 数据适用于 MySQL,但在 PostgreSQL 数据库上失败
- python - 如何使用 Selenium [Python] 获取 iframe 源
- java - M1 Mac 上 System.getProperty("os.arch") 的值?
- git - 如何从以前的 Git 提交中删除文件
- c# - 从 Xamarin.Forms 调用 Android 函数