[英]How do I create a SQL Query that returns a column filtering entries that are more than a week old?
我有一個 data.table 使用 SQL 具有以下相關列:
目前我的查詢成功返回列,除了每個縣未發送的申請數量和 state 有客戶外,我還可以在其中看到申請總數
我的問題:我正在嘗試創建一個名為“7 天前已接受未發送的應用程序”的新列,該列提供當前日期前一周已發送應用程序且縣和 state 未發送任何產品的應用程序數量. 有沒有人對如何做到這一點有任何建議?
SELECT
state,
county,
COUNT (CASE WHEN customer_registration IS NOT NULL THEN 1 END) AS "Accepted Apps Total",
COUNT (CASE WHEN customer_registration IS NOT NULL AND product_issued_date IS NULL THEN 1 END) AS "Unmailed Apps Total", /* below is where I want to write the code to determine unissued products that have been applied for in more than a week */
COUNT() AS 'Unsent Apps Accepted 7+ Days Ago'
FROM
public.product_data
GROUP BY
state, county
ORDER BY
state, county
這里對application_date
列的類型有些疑惑:是DateTime還是varchar。 如果您發現自己擔心格式為 SQL 的日期值,那么您的架構就出現了嚴重錯誤!
假設正確的DateTime
選項超過錯誤和損壞的varchar
選項,您可以使用conditional aggregation 。 到底是什么樣子取決於您使用的是哪種數據庫產品(每個產品的日期函數都略有不同)。 Sql 服務器看起來像這樣:
SELECT
state
,county
,COUNT (case when customer_registration is not null then 1 end) as "Accepted Apps Total"
,COUNT(case when customer_registration is not null and product_issued_date is null then 1 end) as "Unmailed Apps Total" /* below is where I want to write the code to determine unissued products that have been applied for in more than a week */
,SUM(CASE WHEN
application_date < DATEADD(day, -7, current_timestamp) AND product_issued_date IS NULL
THEN 1 ELSE 0 END) as [Unsent Apps Accepted 7+ Days Ago]
FROM public.product_data
GROUP BY state, county
ORDER BY state, county
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.