sql - 如何使用 date_part 选项在 postgres 中获取不同的日期
问题描述
如何在 PostgreSQL 中获取日期时差
我正在使用以下语法
select id, A_column,B_column,
(SELECT count(*) AS count_days_no_weekend
FROM generate_series(B_column ::timestamp , A_column ::timestamp, interval '1 day') the_day
WHERE extract('ISODOW' FROM the_day) < 5) * 24 + DATE_PART('hour', B_column::timestamp-A_column ::timestamp ) as hrs
FROM table req where id='123';
如果 A_column=2020-05-20 00:00:00 和 B_column=2020-05-15 00:00:00 我想得到 72(以小时为单位)。
是否有可能在第一个中跳过周末(周六和周日),这意味着得到结果为 72 小时(不包括周末时间)
我得到 0
但我需要得到 72 小时
如果如果 A_column=2020-08-15 12:00:00 和 B_column=2020-08-15 00:00:00 我想得到 12(以小时为单位)。
解决方案
我会通过计算周末时间来让数据库处理夏令时来解决这个问题。然后,我将从两个日期值之间的差异中减去中间的周末时间。
with weekend_days as (
select *, date_part('isodow', ddate) as dow
from table1
cross join lateral
generate_series(
date_trunc('day', b_column),
date_trunc('day', a_column),
interval '1 day') as gs(ddate)
where date_part('isodow', ddate) in (6, 7)
), weekend_time as (
select id,
sum(
least(ddate + interval '1 day', a_column) -
greatest(ddate, b_column)
) as we_ival
from weekend_days
group by id
)
select t.id,
a_column - b_column as raw_difference,
coalesce(we_ival, interval '0') as adjustment,
a_column - b_column -
coalesce(we_ival, interval '0') as adj_difference
from weekend_time w
left join table1 t on t.id = w.id;
推荐阅读
- android - Flutter 无法从 app.apk 读取清单信息
- terraform - 如何使用一个 terraform 脚本和不同的变量值管理多个不同环境的部署
- flutter - 如何使用 image_picker 依赖项在颤振中将图像上传到 sqlite 数据库
- keyboard - 使用外接键盘在 Mac 上编程
- reactjs - React JS:在父组件中调用子组件方法(使用打字稿反应)
- php - 在刀片 php 中将英文日期名称转换为日文
- javascript - 在动态组件中访问 nuxt $store
- macos - NSOpenPanel 打破 macOS 上的 UI 测试
- parallel-processing - Joblib、Parallel 和 batch_size
- regex - 匹配特殊字符串后面的文本