SQL - 根据另一列中的日期筛选 1 列的结果

SQL - Filter results for 1 column based on date in another column

我很难想出一个合适的标题。这就是问题所在。我正在尝试逐月确定新用户使用该工具并制定计划的时间。

这是我目前所拥有的

select 
distinct userID, 
MIN(planID), 
MIN(PlanCreated)
from dataBaseName.tableName 
Group by userID

这为我提供了所需的基本信息。我得到了用户和他们创建的第一个计划以及时间。

但是我需要进一步完善它。因为有些用户进入该工具后只创建了计划,使其处于 'Draft' 状态而从未 return。我需要过滤掉超过 3 个月的草稿计划。

有一个 'PlanStatus' 列,根据 'Draft' 状态进行过滤非常简单

where PlanStatus 
is not in 'Draft'

但同样,我只想从结果中删除那些早于 3 个月的计划。

例如。日期格式 - 2017-01-01 00:00:00

我也不确定是否应该先完成此筛选,这样如果他们后来创建了一个计划并将其移出草稿状态,ID 就不会被完全删除。

示例数据:

planID | userID |    PlanCreated         |    PlanStatus |    OtherColumns

  1111 |      2 |    2016-01-17 00:00:00 |    Completed  |    null

  1112 |      1 |    2016-06-31 00:00:00 |    Draft      |    null

  1113 |      2 |    2017-01-24 00:00:00 |    Completed  |    null

  1114 |      3 |    2017-02-04 00:00:00 |    Draft      |    null

  1115 |      1 |    2017-03-12 00:00:00 |    Draft      |    null

预期结果:

planID | userID |    PlanCreated         |    PlanStatus |    OtherColumns

  1111 |      2 |    2016-01-17 00:00:00 |    Completed  |    null

  1114 |      3 |    2017-02-04 00:00:00 |    Draft      |    null

  1115 |      1 |    2017-03-12 00:00:00 |    Draft      |    null

请帮忙

首先,您是从哪里学会使用 select distinct 和聚合函数的。正确的语法是:

select userID, min(planID), min(PlanCreated)
from dataBaseName.tableName 
Group by userID;

不需要distinct。那么你想要一个where。这是一种方法:

select userID, min(planID), min(PlanCreated)
from dataBaseName.tableName 
where not (status = 'draft' and plandate < '2017-01-01')
Group by userID;

请注意,日期函数和常量可能因数据库而异。

试试这个:

SELECT userID, MIN(planID) , MIN(PlanCreated) FROM dataBaseName.tableName 
WHERE  NOT (status = 'draft' AND DATEDIFF(DAY,   plancreated, getDate()) > 90)
GROUP BY userID