英文:
In SQL: How to concat hour and minute (stored as integers in a separate column) with the date part of a timestamp?
问题
我正在构建一个 Grafana 仪表板,需要应用日期筛选器。
在构建分析时,我正在使用 SQL 查询一个Postgres数据库,日期看起来像这样:
id | timestamp_column | start_time | end_time |
---|---|---|---|
1 | 2023-04-16 16:00:00.000 | 1400 | 1900 |
2 | 2023-04-17 16:00:00.000 | 100 | 900 |
为了能够将其用作筛选器,我希望输出如下:
id | new_timestamp_start | new_timestamp_end |
---|---|---|
1 | 2023-04-16 14:00:00.000 | 2023-04-16 19:00:00.000 |
2 | 2023-04-17 01:00:00.000 | 2023-04-17 09:00:00.000 |
时间戳列的类型为 timestamp,而 start_time 和 end_time 列的类型为 int,请注意,时间 0100 和 0900 存储为 100 和 900。
非常感谢您的所有帮助!
祝好!
英文:
I'm building a Grafana dashboard where I need to apply a date filter.
I'm querying a Postgres database using SQL when I'm building the analysis and the date looks like the following:
id | timestamp_column | start_time | end_time |
---|---|---|---|
1 | 2023-04-16 16:00:00.000 | 1400 | 1900 |
2 | 2023-04-17 16:00:00.000 | 100 | 900 |
I would like the output to be the following in order for me to be able to use it as a filter:
id | new_timestamp_start | new_timestamp_end |
---|---|---|
1 | 2023-04-16 14:00:00.000 | 2023-04-16 19:00:00.000 |
2 | 2023-04-17 01:00:00.000 | 2023-04-17 09:00:00.000 |
The timestamp column is of type timestamp and the start_time and end_time columns are of type int and note that the time 0100 and 0900 therefore is stored as 100 and 900.
Super thankful for all help!
Regards
答案1
得分: 1
这是使用日期和间隔算术的一种方法来实现的:
select id,
date_trunc('day', timestamp_column)
+ start_time / 100 * interval '1 hour'
+ start_time % 100 * interval '1' minute as new_timestamp_start,
date_trunc('day', timestamp_column)
+ end_time / 100 * interval '1 hour'
+ end_time % 100 * interval '1' minute as new_timestamp_end
from mytable
DB Fiddle上的演示 - 我稍微修改了数据,以便考虑分钟:
id | new_timestamp_start | new_timestamp_end |
---|---|---|
1 | 2023-04-16 14:00:00 | 2023-04-16 19:00:00 |
1 | 2023-04-16 01:00:00 | 2023-04-16 09:50:00 |
英文:
Here is one way to do it with date and interval arithmetics:
select id,
date_trunc('day', timestamp_column)
+ start_time / 100 * interval '1 hour'
+ start_time % 100 * interval '1' minute as new_timestamp_start,
date_trunc('day', timestamp_column)
+ end_time / 100 * interval '1 hour'
+ end_time % 100 * interval '1' minute as new_timestamp_end
from mytable
The idea is to break down the integer column into hours and minutes using division and modulo, then perform the date arithmetics.
Demo on DB Fiddle - I slightly modified the data so minutes come into play as well:
id | new_timestamp_start | new_timestamp_end |
---|---|---|
1 | 2023-04-16 14:00:00 | 2023-04-16 19:00:00 |
1 | 2023-04-16 01:00:00 | 2023-04-16 09:50:00 |
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论