最小日期范围与其他日期

时间:2017-05-12 23:09:38

标签: sql sql-server sql-server-2012

我试图获取出现在特定日期范围之间的用户记录数,特别是每个唯一身份用户的最小值(日期)和最小值(日期)+ 14天。我已查看此链接 SQL HAVING BETWEEN a date range 但这不是我想要的。以下是我与之合作以及我尝试做过的事情的一个例子

+----+------------+
| ID | ServiceDt  |
+----+------------+
| 10 | 2017-03-02 |
| 10 | 2017-03-05 |
| 10 | 2017-03-06 |
| 10 | 2017-03-14 |
| 10 | 2017-03-27 |
| 11 | 2017-03-10 |
| 11 | 2017-03-19 |
| 11 | 2017-04-02 |
| 11 | 2017-04-14 |
| 11 | 2017-04-23 |
| .. | ..         |

查询是:

SELECT ID, COUNT(ServiceDt) AS date_count 
FROM (
     SELECT ID, ServiceDt
     FROM tbl 
     GROUP BY ID, ServiceDt
     HAVING ServiceDt BETWEEN MIN(ServiceDt) AND DATEADD(day, +14, MIN(ServiceDt))
) AS R1
GROUP BY ID

当我执行上述查询时,我得到以下结果。

+----+------------+
| ID | date_count |
+----+------------+
| 10 | 5          |
| 11 | 5          |
| .. | ..         |

我也尝试过使用CONVERT(date, ...),但是我得到了相同的结果表。我希望结果是

+----+------------+
| ID | date_count |
+----+------------+
| 10 | 4          |
| 11 | 2          |
| .. | ..         |

有人可以指导我如何获得我想要的输出,谢谢

2 个答案:

答案 0 :(得分:1)

使用窗口功能:

select id, count(*)
from (select t.*, min(servicedt) over (partition by id) as min_sd
      from tbl t
     ) t
where servicedt <= dateadd(day, 14, min_sd)
group by id;

答案 1 :(得分:0)

另一个选择是使用eval.in获取每个ServiceDt的第一个id,并在where子句中使用该select id, count(*) as date_count from t cross apply ( select top 1 i.ServiceDt from t i where i.Id = t.Id order by i.ServiceDt ) x where t.ServiceDt <= dateadd(day,14,x.ServiceDt) group by id

+----+------------+
| id | date_count |
+----+------------+
| 10 |          4 |
| 11 |          2 |
+----+------------+

rextester演示:cross apply()

返回:

var els = document.getElementById('MTG_INSTR$2')