【问题标题】:Ranking by date in SQL but ignoring dates <3 days together在 SQL 中按日期排序,但忽略 <3 天的日期
【发布时间】:2015-11-12 12:41:25
【问题描述】:

我想按日期对一些数据进行排序以获得顺序列表 (1, 2, 3),但忽略一起

例如:

11/10/2015 = 1
11/11/2015 = 2
11/12/2015 = NULL (within 3 days of previous date)
11/15/2015 = 3

请问有什么有效的方法吗?提前谢谢你。

【问题讨论】:

  • 您使用的是哪个 DBMS?后格雷斯?甲骨文?
  • Microsoft SQL Server 2008 R2

标签: sql sql-server date sql-server-2008-r2 rank


【解决方案1】:

我认为你会做这样的事情。了解 RDBMS 会有所帮助。

with date_lags as
    (
        select
            date,
            lag(date) over(order by date) as last_date
        from
            table
    )
select
    date,
    rank() over(order by date) as the_rank
from
    date_lags
where
    datediff(day, last_date, date) >= 3;

【讨论】:

  • Microsoft SQL Server 2008 R2
【解决方案2】:

这有点挑战性,因为您没有lag() 或累积和。但是,您可以使用outer apply(或子查询)来实现它:

select e.*,
       (case when CountFlag = 1
             then row_number() over (partition by CountFlag order by e.date)
        end) as newcol
from example e outer apply
     (select top 1 (case when e.date >= dateadd(day, 3, e2.date) then 1 else 0 end) as CountFlag
      from example e2
      where e2.date < e.date
      order by e2.date desc
     ) eprev;

这使用了一个逻辑技巧来获取NULL 值。注意没有WHERE,所以所有的值都被分配了一个等级。外部查询对case 条件和partition by 子句使用相同的列。

【讨论】:

  • 当两个日期相同时,这会在新列中创建 NULL
  • 将子查询中的&lt; 替换为&lt;=
  • 好的,谢谢。如何通过分区为数据集中的每个人(id)分别执行此操作?这个可以和分区结合吗?
  • @user2964644 。 . .通过在子查询中添加类似e2.person = e.person 的内容。
猜你喜欢
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多