sql - 在 postgreSQL 中一天超过 24 小时
问题描述
假设我有这个架构:
create table rental (
id integer,
rental_date timestamp,
customer_id smallint,
return_date timestamp,
);
运行此查询会返回奇怪的结果:
select customer_id, avg(return_date - rental_date) as "avg"
from rental
group by customer_id
order by "avg" DESC
它显示:
customer_id|avg_rent_duration |
-----------|----------------------|
315| 6 days 14:13:22.5|
187|5 days 34:58:38.571428|
321|5 days 32:56:32.727273|
539|5 days 31:39:57.272727|
436| 5 days 31:09:46|
532|5 days 30:59:34.838709|
427| 5 days 29:27:05|
555|5 days 26:48:35.294118|
...
599 rows
为什么会有像5 days 34:58:38
,5 days 32:56:32
等等这样的值?我以为一天只有24小时,也许我错了。
编辑
在这里演示:http ://sqlfiddle.com/#!17/caa7a/1/0
样本数据:
insert into rental (rental_date, customer_id, return_date)
values
('2007-01-02 13:10:06', 1, '2007-01-03 01:01:01'),
('2007-01-02 01:01:01', 1, '2007-01-09 15:10:06'),
('2007-01-10 22:10:06', 1, '2007-01-11 01:01:01'),
('2007-01-30 01:01:01', 1, '2007-02-03 22:10:06');
解决方案
您必须使用justify_interval()
功能调整间隔:
select customer_id, justify_interval(avg(return_date - rental_date)) as "avg"
from rental
group by customer_id
order by "avg" DESC;
见官方文档:
justify_days
使用和调整间隔justify_hours
,并进行额外的符号调整
尽管如此,它并没有解释为什么不使用操作的结果会很奇怪justify_interval()
(换句话说,为什么我们必须应用这个函数)
注意:感谢@a_horse_with_no_name的评论
推荐阅读
- c# - 在带有 C# 的 Visual Studio 中使用 Windows 窗体,有没有办法让 Graphics.DrawEllipse 函数完全按照指定绘制椭圆?
- vuejs2 - Vue多选表单相互独立
- javascript - 无法使用 jQuery 选择元素的兄弟姐妹
- python-3.x - python3:socket.gethostbyaddr():“未知主机”与“主机名查找失败”
- c++ - R与C++的联动(Rccp)
- javascript - 将复选框方形选项更改为图像
- python - 如何解决?AttributeError:'NoneType'对象没有属性'head'
- python - 如何在 Python Gekko 中求解积分?
- java - 使用 @OneToMany 时 JPA 结果无限循环
- html - 当仅使用 CSS 和 HTML 将鼠标悬停在不同的图像上时,如何显示不同的文本?