You need to enable JavaScript to run this app. PostgreSQL中如何计算不同表两个日期之间的天数差?
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中如何计算不同表两个日期之间的天数差?

问题原因

PostgreSQL 未内置datediff函数,两个date类型字段直接做减法运算,返回的结果就是间隔的天数,不需要调用专门的函数。

修改后的查询语句
select 
   t1."group",
   t2.start_date - t1.event_date as date_diff_days,
   count(distinct t1.employee_id)
from t1 join t2 on t1.project_id = t2.id
where true
  and t1.cummulative_manhour > 0
  and t1.company_id in ('a', 'b')
  and t1.event_date = '2021-05-17'
  and t1.project_id = '2900'
group by 
  t1."group",
  t2.start_date,
  t1.event_date
补充说明
  • 如果需要不区分日期前后顺序取正数的天数差,可以用abs(t2.start_date - t1.event_date)替代原有差值计算逻辑
  • 如果待计算的字段是timestamp类型而非date类型,计算天数差可以用EXTRACT(DAY FROM (t2.start_timestamp - t1.event_timestamp))实现

内容的提问来源于stack exchange,提问作者nomnom3214

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 13:15:02