繁体   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