mysql - MySQL 从具有不同条件的一张表中选择字段
问题描述
我需要你的 mysql 查询帮助。我有一张表“指标”:
create table metrics
(
guid binary(16) not null
primary key,
entry_guid binary(16) not null,
customer_guid binary(16) null,
metrics varchar(30) not null,
value int not null,
`_created` timestamp null,
`_updated` timestamp null
);
所以,我正在尝试做这样的事情:
SELECT t1.entry_guid as entry_guid, SUM(t1.`value`) as last_week, SUM(t2.`value`) as last_month
FROM metrics as t1, metrics as t2
WHERE t1.`_created` > NOW() - INTERVAL 7 DAY OR t2.`_created` > NOW() - INTERVAL 1 MONTH
GROUP BY t1.entry_guid
但结果我得到了使用 SUM() 函数的相同奇怪结果
entry_guid last_week last_month
1 4613 4613
2 207 207
3 6003 6003
4 9108 9108
此外 SUM() func 的结果很奇怪,因为我只有 300 行,每行中的 'value' 字段等于1,所以最大总和必须很小。
所以,查询
SELECT t1.entry_guid as entry_guid, SUM(t1.`value`) as sum
FROM metrics as t1
GROUP BY t1.entry_guid
给我
entry_guid sum
0x34303535636637643538396665633265 21
0x34313830656231666665393131326635 21
0x34336537663033653963303437356165 1
0x34363061653730313738313263386264 44
我需要从一张表中获取 SUM('value'),但条件不同。你能告诉我怎么做吗?先感谢您。
解决方案
使用条件聚合:
SELECT m.entry_guid as entry_guid,
SUM(CASE WHEN m.`_created` > NOW() - INTERVAL 7 DAY THEN t1.`value` ELSE 0 END) as last_week,
SUM(CASE WHEN m.`_created` > NOW() - INTERVAL 1 MONTH THEN t2.`value` ELSE 0 END) as last_month
FROM metrics m
GROUP BY m.entry_guid;
推荐阅读
- delphi - 如何在代码中映射域上的网络驱动器
- r - 获取向量列表中每个向量的第 n 个元素并放入新列表 R
- html - 在 VSCode 中注释内部 CSS 的快捷方式
- angular - 具有共享布局和功能模块的路由
- ios - ios 15 将标准输出重定向到 textView
- python - sum() 不适用于 Timedelta 对象列表
- python - 在 deepspeech 内部训练期间出错:无法使用模型配置调用 ThenRnnForward:[rnn_mode, rnn_input_mode, rnn_direction_mode]
- php - 满足条件时不进入while循环
- python - 硒自动登录失败没有这样的元素:无法找到元素
- azure-devops - 无法从 Azure Devops CLI 任务运行正确的 Azure CLI 命令(错误请求)