简体   繁体   English

SQL - 其中 MIN 日期正好是 7 天前

[英]SQL - where MIN date is exactly 7 days ago

I need to select only the lines where MIN date is 7 days ago.我只需要选择 MIN 日期为 7 天前的行。 I have Customers with invoices, the invoices have due dates.我有发票的客户,发票有到期日。 I can select MIN due date of these invoices per Customer.我可以为每个客户选择这些发票的最小到期日。 I am now stuck as I cannot select only the Customers who are exactly 7 days overdue with their oldest invoice.我现在卡住了,因为我不能只选择最旧发票过期 7 天的客户。

This is what I have:这就是我所拥有的:

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

I tried adding:我尝试添加:

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

This does not work.这不起作用。 What am I doing wrong?我究竟做错了什么?

Thanks.谢谢。

Use a having clause to filter the minimum date:使用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';

Note that date functions are highly database specific.请注意,日期函数是高度特定于数据库的。 The above is standard SQL, but the exact syntax depends on the database you are using.以上是标准 SQL,但确切的语法取决于您使用的数据库。

Thank you, Gordon, you put me on the right track!谢谢你,戈登,你让我走上了正轨! This is what eventually did the trick:这就是最终成功的秘诀:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM