按日期范围消除行

时间:2017-10-09 20:01:46

标签: sql sql-server sql-server-2008 tsql

我有以下内容:

Index   dateOfInquiry   
649454      2016-02-05 
649455      2016-02-05   

我有这个问题:

SELECT COUNT(a.dateOfInquiry) as NumberRecords
FROM 
( 
    SELECT ROW_NUMBER() OVER(ORDER BY dateOfInquiry ASC) 
        Id, dateOfInquiry

    FROM 
    Table
) a 

INNER JOIN 
(
    SELECT ROW_NUMBER() OVER(ORDER BY dateOfInquiry ASC) 
            Id, dateOfInquiry

    FROM 
        Table
) 
b 

ON b.ID = a.ID + 1 
WHERE ABS( DATEDIFF(d, a.dateOfInquiry, b.dateOfInquiry ) ) > 14
GROUP BY a.strTransactionID 

我要做的是每14天只返回1条记录。所以我在上面的数据集中想要1,但我得到0(它消除了两个记录,因为它们之间没有14天)

此外,如果有更多记录并且行为不太正确,它会变得更复杂。如果我在1日,2日,3日等到15日都有记录,我仍然只想要1条记录,然后在16日或之后的下一条记录再次开始计数,忽略进一步的记录,直到差异为止超过14天。

基本上我想将记录计为1,然后忽略所有其他记录,直到14天为止。

另一个样本和我想要的结果是2:

Index   dateOfInquiry   
649454      2016-02-01  <- count
649455      2016-02-12  -ignore (<l4 past 649454)
649456      2016-02-12  -ignore (<l4 past 649454)
649457      2016-02-17  <- count
649458      2016-02-22  -ignore (<l4 past 649457)
649459      2016-02-25  -ignore (<l4 past 649457)

2 个答案:

答案 0 :(得分:1)

使用outer apply()获取每行的下一个符合条件的行的id,并使用递归common table expression从头开始并继续前进:

;with cte as (
  select t.id, t.dateOfInquiry, x.next_id
  from t
    outer apply (
      select top 1 next_id = i.id
      from t as i
      where i.dateOfInquiry > dateadd(day,14,t.dateOfInquiry)
      order by dateofInquiry, id asc
    ) x
)
, r_cte as (
    --anchor row(s) / starting row(s)
  select 
      id
    , dateOfInquiry
    , next_id
  from cte t
  where not exists (
    select 1
    from cte as i
    where i.id < t.id
    )
  union all
  --recursion starts here
  select 
      c.id
    , c.dateOfInquiry
    , c.next_id
  from cte c
    inner join r_cte p
      on c.id = p.next_id
)
select id, dateOfInquiry
from r_cte

rextester演示:http://rextester.com/PIMVPM32168

返回:

+--------+---------------+
|   id   | dateOfInquiry |
+--------+---------------+
| 649454 | 2016-02-01    |
| 649457 | 2016-02-17    |
+--------+---------------+

答案 1 :(得分:1)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@latest/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>

<canvas id="chartBox"></canvas>

你应该提供真实的情景。

尝试我的脚本和其他样本数据。我在递归CTE中使用what is the use of index column in you requirement ? 函数。所以如果没有比这更好的解决方案,那么我认为2 ROW_NUMBER将是一种更好,更容易理解的方法。

CURSOR
相关问题