mysql - MySQL为每日报告创建自定义日期范围
问题描述
mysql 8.0
我有看起来像这样的数据集:
user_id transaction_time item_price
1 2020-01-01 13:00:00 100
1 2020-01-01 18:00:00 100
1 2020-01-01 19:00:00 100
1 2020-01-01 23:00:00 100
1 2020-01-02 04:00:00 100
1 2020-01-02 09:00:00 100
通常,如果我想找到每日价格的总和(价格),我会这样做
select date(transcation_time) as dt
, sum(item_price) as sum_price
from table
group by date(transaction_time)
这将输出
dt sum_price
2020-01-01 400
2020-01-02 200
但是,我不想将价格从到2020-01-01
求和,而是将价格从到的总和标记为2020-01-01 00:00:00
2020-01-01 23:59:59
2020-01-01 18:00:00
2020-01-02 06:00:00
2020-01-01
所以
2020-01-01 sums prices from 2020-01-01 18:00:00 ~ 2020-01-02 06:00:00
2020-01-02 sums prices from 2020-01-02 18:00:00 ~ 2020-01-03 06:00:00
2020-01-03 sums prices from 2020-01-03 18:00:00 ~ 2020-01-04 06:00:00
等等...
那么我得到的聚合将如下所示:
dt sum_price
2020-01-01 500
2020-01-02 100
请注意,第一行没有添加,因为 13:00:00 不在 18:00:00 ~06:00:00
我怎样才能做到这一点?
解决方案
我认为您只想减去 6 小时 - 或添加 18 小时:
select date(transaction_time + interval -6 hour) as dt,
sum(item_price) as sum_price
from table
group by dt;
如果你真的只想要 12 小时,那么添加一个where
子句:
select date(transaction_time + interval -6 hour) as dt,
sum(item_price) as sum_price
from table
where time(transaction_time) >= '18:00:00' or
time(transaction_time) < '06:00:00'
group by dt
推荐阅读
- java - 如何以编程方式在eclipse java中重命名文件时取消绑定键盘快捷键F2
- java - 当嵌套 JSON 中出现相同的字段名称时,将 JSON 解析为 java 对象
- mysql - 如何在 SQL 中获取一个常量值
- google-app-maker - 使用 Google 网上论坛获取访问权限 - 不起作用
- javascript - 显示当前日期以及额外的 30 天计算 - JS
- php - 提交 Multipart/form-data 后不获取 POST 变量
- nativescript - 如何使用 Visual Studio Online/Azure 开发操作工具为 nativescript 设置 CI/CD
- django - 如何在 django 中上传和查看图像
- wpf - How can I connect TriangleIndices(a.k.a. Triangles)?
- c# - 在 ASP MVC 5 中添加新视图时出现问题