我正在为每条记录查找从开始日期起的未来30天内的记录数
我有一张桌子:
Patid Start_date
1234 1/1/2015
1234 1/10/2015
1234 1/30/2015
1234 2/19/2015
1234 3/5/2015
1234 3/6/2015
1234 3/7/2015
我想写一个简单的sql查询,它应该给我以下结果:
patid: Start_Date #of Records in Next 30 Days
1234 1/1/2015 2
1234 1/10/2015 2
1234 1/30/2015 1
1234 2/19/2015 3
1234 3/5/2015 2
1234 3/6/2015 1
1234 3/7/2015 0
谨致问候,阳光
在通用SQL中,最简单的方法是使用相关的子查询:
select t.*,
(select count(*)
from table t2
where t2.patid = t.patid and
t2.start_date > t.start_date and
t2.start_date <= t.start_date + interval '30 days'
) as Next30Days
from table t;
这使用了ANSI标准语法进行日期运算——这是一个主要在违反中观察到的标准。每个数据库似乎都有自己的日期统计规则。