-1

我正在尝试从每条记录的开始日期开始的接下来 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

最好的问候,阳光

4

1 回答 1

1

在通用 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 标准语法进行日期算术——在违规行为中最常见的标准。每个数据库似乎都有自己的按摩日期规则。

于 2015-02-06T20:50:35.880 回答