簡體   English   中英

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

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

我只需要選擇 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())

這不起作用。 我究竟做錯了什么?

謝謝。

使用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,但確切的語法取決於您使用的數據庫。

謝謝你,戈登,你讓我走上了正軌! 這就是最終成功的秘訣:

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