[英]How do I create a SQL Query that returns a column filtering entries that are more than a week old?
I have a data.table using SQL that has the following relevant columns:我有一个 data.table 使用 SQL 具有以下相关列:
Currently my query successfully returns columns that where I can see the total amount of applications in addition to the number of unsent applications for each county and state that there are customers目前我的查询成功返回列,除了每个县未发送的申请数量和 state 有客户外,我还可以在其中看到申请总数
My question: I am trying to create a new column called 'Unsent Apps Accepted 7+ Days Ago' which delivers the number of applications where the application has been sent a week before the current date and no product has been sent out by county and state. Does anyone have any advice on how to do this?我的问题:我正在尝试创建一个名为“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
There's some doubt here about the type of the application_date
column: whether it's DateTime or varchar.这里对
application_date
列的类型有些疑惑:是DateTime还是varchar。 If you ever find yourself worrying about the format a date value with SQL, you've done something horribly wrong with your schema!如果您发现自己担心格式为 SQL 的日期值,那么您的架构就出现了严重错误!
Assuming the correct DateTime
option over the wrong and broken varchar
option, you can use conditional aggregation .假设正确的
DateTime
选项超过错误和损坏的varchar
选项,您可以使用conditional aggregation 。 What exactly that looks like depends no which database product you're using (the date functions are a little different in each product).到底是什么样子取决于您使用的是哪种数据库产品(每个产品的日期函数都略有不同)。 Sql Server would look like this:
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.