【问题标题】:SQL Query to get the distinct dates which are at least 10 days apartSQL 查询以获取至少相隔 10 天的不同日期
【发布时间】:2020-10-08 07:54:55
【问题描述】:

我有一张包含日期和姓名的表格。我想按名称和日期对结果进行分组,条件是选择的结果日期至少相隔 10 天。 (从该名称出现在表中的第一个日期开始)

这是一个例子:

________________________
Names    |      Dates    
-----------------------
John     |      2-2-2000
________________________
John     |      5-2-2000
________________________
John     |      16-2-2000
________________________
John     |      17-2-2000
________________________
John     |      20-2-2000
________________________
John     |      31-2-2000
________________________
John     |      5-3-2000
________________________
John     |      14-3-2000
________________________

查询的输出应该是这些值的计数之和 (John,2-2-2000),(John,16-2-2000),(John,31-2-2000),(John, 14-3-2000) 即 4.

如何在 SQL Server 中为此编写查询?

【问题讨论】:

  • 你应该用更多的行来扩展你的数据,这样它就更有代表性。例如,如果 John 有更多行,日期为 '25-2-2000''15-3-2000',结果会是什么样子?
  • @GMB ,我已经编辑了问题。
  • 谢谢。旁注:2 月 31 日不是有效日期。

标签: sql sql-server date join recursive-query


【解决方案1】:

您的问题不清楚。与您想要的结果一致的是,您希望计算与前一行的差距为 10 天以上的行。为此,只需使用lag():

select count(*)
from (select t.*,
             lag(date) over (partition by name) as prev_date
      from t
     ) t
where prev_date is null or prev_date < dateadd(day, -10, date);

使用select * 获取记录列表。

【讨论】:

    【解决方案2】:

    这有点棘手,因为您需要跟踪“选择”的最后一行以选择下一行。这意味着您需要一种迭代过程,这反过来又建议递归查询:

    with 
        data as (
            select t.*, row_number() over(partition by names order by dates) rn
            from mytable t
        ),
        rcte as (
            select d.*, dates dates_base from data d where rn = 1
            union all
            select 
                d.*, 
                case when d.dates >= dateadd(day, 10, r.dates_base) then d.dates else r.dates_base end
            from rcte r
            inner join data d on d.rn = r.rn + 1 and d.names = r.names  
        )
    select names, count(distinct dates_base) res from rcte group by names
    

    Demo on DB Fiddlde

    姓名 |资源 :---- | --: 约翰 | 4

    【讨论】:

    • 我有点困惑。问题中提到的列名发生了变化。现在,当我尝试运行查询时,我得到了所有错误,您能更改查询吗? names = EmployeeCode dates = DistussionDate 表名是 Oneoonefeedback。请原谅我 。我对 SQL 有点陌生
    • @VishnuSayanthAV:这使用列datesnames,就像你的问题一样。您也可以参考我在回答中链接的演示。
    猜你喜欢
    • 2019-03-23
    • 2021-08-10
    • 1970-01-01
    • 2019-11-15
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    相关资源
    最近更新 更多