gpt4 book ai didi

sql - 如何在sql server中获得一个负数row_number

转载 作者:行者123 更新时间:2023-12-04 23:26:08 27 4
gpt4 key购买 nike

我有一组带有 DateTime 的数据,比如 CalculatedOn 我想要的是从当前日期开始 getdate() 并获取当前日期之前的 x 数量的记录,以及之后相同数量的记录。

如果 x = 50 那么现在之前的 50 个和现在之前的 50 个。我在想 rownumber() 将是完美的选择,但我想不出如何对先前的负数行和 future 的正数行进行编号。

还有一个问题,如果没有 50 个之前或 future 会发生什么,但那会在之后发生。

假设表格只有两列:

create table MyTable
(
Id int not null constraint pk_mytable primary key,
SomeTextIWant nvarchar(50) not null,
CalculateDate DateTime not null
);

结果:

如果今天是 25/04 12:54

然后

Id, SomeTextIWant, CalculatedDate
-- 50 from before now--
-----now here-----
-- 50 from after now--

最佳答案

如果你想在前后获得 50 行,也许这会做你想要的:

with cte1 as (
select top 50 t.*
from table t
where CalculatedDate <= getdate()
order by CalculatedDate desc
),
cte2 as (
select top 50 t.*
from table t
where CalculatedDate > getdate()
order by CalculatedDate
)
select *
from (select * from cte1 union all select * from cte2) t

编辑:

从问题的上下文来看,我不清楚是否确实需要行号。添加起来很容易,though:

(select top 50 t.*,
- row_number() over (order by CalculatedDate desc) as rownumber
from table t
where CalculatedDate <= getdate()
order by CalculatedDate desc
)
union all
(select top 50 t.*,
row_number() over (order by CalculatedDate) as rownumber
from table t
where CalculatedDate > getdate()
order by CalculatedDate
)

您实际上可以将这些组合成一个查询:

select t.*,
((case when CalculatedDate < getdate() then -1 else 1 end) *
(row_number() over (partition by (case when CalculatedDate < getdate() then 1 else 0 end)
order by (case when CalculatedDate < getdate() then CalculatedDate end) desc,
CalculatedDate asc
)
)) as rn
from table t;

您可以将它放在子查询中并选择 rn 在 -50 到 50 之间的位置。

但是,我不确定如何处理第 0 行,并且该问题没有提供有关如何处理与 getdate() 匹配的任何记录的信息(尽管这不太可能)。我认为第一个答案满足了 OP 的需要。

关于sql - 如何在sql server中获得一个负数row_number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23292254/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com