MySQL 查询按日期分组(12 小时间隔)
我编写了一个sql查询来获取在一段时间内创建的用户数量以绘制图形(grafana或chart js),我的sql查询是
SELECT
date(user.created_date) as "time",
count(distinct user.id) as Number Of User,
status as status
FROM user
WHERE
created_date >= FROM_UNIXTIME(1649635200) AND
created_date < FROM_UNIXTIME(1649894399)
GROUP BY user.status, date(user.created_date)
ORDER BY date(user.created_date)
在这个查询中创建日期是从前端动态传递的, 现在我得到的结果是这样的
现在,每当我选择过去 24 小时/12 小时的日期过滤器时,有些结果就不存在,
有没有办法修改我的 sql 查询,以按 12 小时间隔的created_date 进行分组 例如,现在查询结果是 11/04/2022 - 5 个用户(已创建应用程序) 我想要这样的查询结果 11/04/2022 00:00:00 2 - 2 个用户创建于 11/04/2022 12:00:00 - 已创建 3 个用户
I wrote a sql query for getting number of users created in a period of time for plotting graph (grafana or chart js) , and my sql query is
SELECT
date(user.created_date) as "time",
count(distinct user.id) as Number Of User,
status as status
FROM user
WHERE
created_date >= FROM_UNIXTIME(1649635200) AND
created_date < FROM_UNIXTIME(1649894399)
GROUP BY user.status, date(user.created_date)
ORDER BY date(user.created_date)
Here in this query created date is passed dynamically from front-end,
Now i am getting the result like,
Now whenever i select the date filter from last 24 hours/12 hours some of the result is not there,
Is there is any way to modify my sql query to group by created_date with 12 hour interval
For Example, Now query result is 11/04/2022 - 5 Users(Application Created) I want query result like this 11/04/2022 00:00:00 2 - 2 users created 11/04/2022 12:00:00 - 3 users created
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在grafana中有一个归档的
$__timeFrom()
和$__timeTo()
在此基础上我重写了我的查询:
In grafana there is a filed
$__timeFrom()
and$__timeTo()
On the basis of this I rewrite my query:
如果您通过在
组中使用此扩展,则将获得12小时的分组。
如果您拥有PRIV,则可以声明存储的功能,以使其更易于阅读。
您也可以执行此操作
然后,即使该功能在查询中出现3次,
,因为它已声明为
确定性
它只会调用一次每行一次。更完整的写入在这里。If you use this expresion in your
GROUP BY
, you'll get a 12-hour grouping.You can, if you have the priv, declare a stored function to make this easier to read.
Then you can do
Even though the function appears three times in your query, because it's declared
DETERMINISTIC
it only gets called once per row.More complete writeup here.