SQL-MIN日期恰好是7天前

时间:2020-10-07 16:30:10

标签: sql oracle where-clause min

我只需要选择MIN日期为7天前的行。 我有带发票的客户,发票有到期日。我可以为每个客户选择这些发票的最短到期日期。我现在陷入困境,因为我无法只选择过期最晚7天的客户。

这就是我所拥有的:

select
 customerID,
 MIN(dueDate) as min_due_date
 from invoices
 where (invoiceStatus NOT IN ('PaidPosted','Cancelled'))
 and (entity = 'HQ')
 group by (customerID)

我尝试添加:

and min_due_date = dateadd(day, -7, SYSDATE())

这不起作用。 我在做什么错了?

谢谢。

2 个答案:

答案 0 :(得分:0)

使用having子句来过滤最小日期:

select customerID, min(dueDate) as min_due_date
from invoices
where invoiceStatus not in ('PaidPosted', 'Cancelled') and
      entity = 'HQ'
group by customerID
having min(duedate) = current_date - interval '7 day';

请注意,日期函数高度依赖于数据库。上面是标准的SQL,但是确切的语法取决于您使用的数据库。

答案 1 :(得分:0)

谢谢你,戈登,你让我走上了正轨! 最终,这就是窍门:

select customerID, min(dueDate) as min_due_date
from invoices
where invoiceStatus not in ('PaidPosted', 'Cancelled') and
      entity = 'HQ'
having MIN(dueDate) = trunc(sysdate) -7
group by customerID
相关问题