我有一组DateTime
的数据,比如CalculatedOn
我希望从当前日期getdate()
开始,并获得x
的数量当前日期之前的记录,以及之后的相同金额。
如果x = 50
在现在之前是50,在现在之前是50。我当时认为rownumber()
对于这一点是完美的,但是我想不出如何将先前为负的行数和未来的正数。
还有一个问题是,如果没有50个先前或将来会发生什么,但那将会发生。
假设该表只有两列:
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--
答案 0 :(得分:3)
如果你想在前后获得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
编辑:
从问题的上下文中我不清楚是否确实需要行号。 thoug:
很容易添加(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;
您可以将其放在子查询中,并选择介于-50和50之间rn
的位置。
但是,我不知道如何处理第0行,并且该问题没有提供有关如何处理与getdate()
匹配的任何记录的信息(不太可能)。我认为第一个答案是OP需要的。
答案 1 :(得分:1)
您可以使用两个CTE,一个用于过去,一个用于将来的日期,然后将ROW_NUMBER
与ASC
和DESC
一起使用,在此之前与{{1}相乘和concat all:
-1
答案 2 :(得分:0)
试试这个......
With myCte
As
(
Select top 2 column1,column2 from YourTable where yourdate > '2014-04-23'
union
Select top 2 column1,column2 from YourTable where yourdate < '2014-04-23'
) select ROW_NUMBER() over (order by column1) as RNO,* from myCte
答案 3 :(得分:0)
使用RowNumber
SELECT TOP 50 ROW_NUMBER() OVER (ORDER BY CalculateDate) AS RowNum,
id, SomeTextIWant, CalculateDate
FROM MyTable
WHERE CalculateDate > @Date
UNION ALL
SELECT TOP 50 -ROW_NUMBER() OVER (ORDER BY CalculateDate DESC) AS RowNum,
id, SomeTextIWant, CalculateDate
FROM MyTable
WHERE CalculateDate < @Date