mysql - MySQL如何将两行合二为一
问题描述
你好堆栈溢出,
我正在使用带有下表的 mysql 8:
create table usage_info
(
id bigint auto_increment
primary key,
amount double not null,
timestamp datetime null,
type varchar null
);
示例数据:
id amount timestamp type
--------------------------------------
1 0.123 2020-06-30 12:40:54 A
2 0.098 2020-06-30 15:47:51 B
3 0.456 2020-06-30 16:40:54 A
4 0.101 2020-06-30 17:47:51 B
5 0.123 2020-07-01 12:40:54 A
6 0.098 2020-07-01 15:47:51 B
7 0.456 2020-07-01 16:40:54 A
8 0.101 2020-07-01 17:47:51 B
我可以使用 2 种不同的方法获得每天每种类型的总数
方法一。
select total, type, date from (
select sum(u.amount) as total, u.type, DATE_FORMAT(u.timestamp, "%a-%c-%d-%y") as date
from usage_info u
group by DATE_FORMAT(u.timestamp, "%a-%c-%d-%y"), u.type) as temp;
结果:
total type date
---------------------
0.579 A Tue-6-30-20
0.199 B Tue-6-30-20
0.579 A Wed-7-01-20
0.199 B Wed-8-01-20
方法2。
select case
when type = 'A' then total
end as A,
case
when type = 'B' then total
end as B,
date
from (
select sum(u.amount) as total, u.type, DATE_FORMAT(u.timestamp, "%a-%c-%d-%y") as date
from usage_info u
group by DATE_FORMAT(u.timestamp, "%a-%c-%d-%y"), u.type
) as results;
给出:
A B date
----------------------------
0.579 null Tue-6-30-20
null 0.199 Tue-6-30-20
0.579 null Wed-7-01-20
null 0.199 Wed-7-01-20
但我希望结果看起来像:
A B date
----------------------------
0.579 0.199 Tue-6-30-20
0.579 0.199 Wed-7-01-20
谢谢你的时间!
解决方案
只需使用条件聚合:
select sum(case when type = 'A' then u.amount end) as total_a,
sum(case when type = 'B' then u.amount end) as total_b,
DATE_FORMAT(u.timestamp, "%a-%c-%d-%y") as date
from usage_info u
group by DATE_FORMAT(u.timestamp, '%a-%c-%d-%y');
推荐阅读
- python - 是否有使用 Python 和请求对网站进行身份验证的通用说明?
- youtube - 就像没有 API 密钥的 Youtube 视频一样?
- typescript - 编译后出现TypeScript错误但编译前没有错误
- laravel - Axios 在 Laravel 的 Vue 组件访问数据时给出 undefined
- c++ - 多行字符串上的 QRegularExpression 匹配不起作用
- excel - Workbook.Open 找不到文件
- java - 如何在 Spring Boot 应用程序的请求范围 Bean 中设置值
- swift - X-CallBack 是否在后台线程中工作?
- html - 动画元素在外观上平滑淡入,但在消失时立即隐藏
- google-apps-script - 如何从谷歌应用脚本中的复选框中获取所有选中的单元格?