mysql - 将 2 个不同时间范围的相似查询合并为 1 个,而不是使用 UNION ALL
问题描述
我正在使用 MySQL 5.7,我需要从像这样的表中进行查询
order_id fee created_time
111 10 2020-11-16
222 90 2020-11-01
333 300 2000-10-22
结果应该是最近 1 天(昨天)和最近 30 天的总收入,比如
date_range revenue
1 10
30 400
该专栏date_range
是现在之前的最后 X 天,我可以使用“union all”来做到这一点:
SELECT 1 AS date_range, SUM(fee) FROM test
WHERE created_time >= SUBDATE(CURRENT_DATE, 1) AND created_time < CURRENT_DATE
UNION ALL
SELECT 30 AS date_range, SUM(fee) FROM test
WHERE created_time >= SUBDATE(CURRENT_DATE, 30) AND created_time < CURRENT_DATE
查询非常相似,是否可以将它们组合成一个查询而不是使用union all
?
创建表:
CREATE TABLE test (
order_id INT,
fee INT,
created_time DATETIME
)
插入值:
INSERT INTO test VALUES (111,10,'2020-11-16'),(222,90,'2020-11-01'),(333,300,'2020-10-22')
解决方案
您可以在以下情况下尝试使用案例: https ://dev.mysql.com/doc/refman/5.7/en/case.html
select date_range, sum(fee)
from (
select
case
when created_time between subdate(current_date, 1) and current_date then 1
when created_time between subdate(current_date, 30) and current_date then 30
end case date_range,
fee
from test) t
where date_range is not null
group by date_range
推荐阅读
- python - 如何在 Python 中并行化函数调用
- excel - 用户窗体文本框字体更改(斜体回到默认值)
- flutter - 无法单击其他元素覆盖的带有颤振appium驱动程序的Web元素
- json - Scala - 将嵌套的 json 文件及其关系树拆分为多个 json 文件
- java - 将浮点数舍入到 epsilon
- boolean - 这个布尔转换正确吗?
- reactjs - ReactJS setState 与对象和数组
- html - 为什么在按钮上按 Enter 不会导致:Chrome 中的活动状态?
- html - 使用 ngFor 内的方括号访问对象内的数组
- javascript - 不推荐使用 yAxis 类时,如何更改 Highcharts 图表中 y 轴的高度?