简体   繁体   中英

SQL - where MIN date is exactly 7 days ago

I need to select only the lines where MIN date is 7 days ago. 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.

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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