首页 > 解决方案 > Postgres (SQL) 查找未保留的总天数

问题描述

好吧,说我有一张叫预订的桌子

id (PK)
class (int FK)
name (varchar 64)
start_date (timestamp)
end_date (timestamp)
...etc

今年有很多预订,我正在寻找的是预订活动的总天数。例如,1 月 1 日至 1 月 5 日和 1 月 10 日至 1 月 12 日总共有 7 天,它将从 1 月 6 日至 1 月 9 日排除在外……将此应用于 XX 个月。

标签: sqlpostgresql

解决方案


我假设班级是预订的指标。因此,此查询将返回过去 12 个月保留的总天数。

select class, sum(end_date-start_date)
from table
where start_date between current_date + (-12::int || ' month')::interval and 
current_date
group by class

推荐阅读