簡體   English   中英

如何創建一個 SQL 查詢,該查詢返回超過一周的列過濾條目?

[英]How do I create a SQL Query that returns a column filtering entries that are more than a week old?

我有一個 data.table 使用 SQL 具有以下相關列:

  • customer_registration:每個客戶在申請獲取產品時創建的 8 位客戶代碼
  • state:客戶所在的state
  • 縣:客戶居住的縣
  • application_date:客戶發送訂單接收申請的日期,格式為 MM/DD/YYYY
  • product_issued_date:客戶申請的產品實際發送給他們的日期,格式為MM/DD/YYYY

目前我的查詢成功返回列,除了每個縣未發送的申請數量和 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM