[英]sql server query , each cell's value is next cell - 1
i have a table like below : 我有一个如下表:
id DateFrom
--------------------
1 2000/05/01
2 2000/05/05
3 2000/05/05
4 2000/05/05
5 2000/05/10
6 2000/05/15
7 2000/05/25
and i want to make it like this . 我想这样做。 which DateTo contain the next Date - 1 Day
哪个日期包含下一个日期-1天
id DateFrom DateTo
---------------------------
1 2000/05/01 2000/05/04
2 2000/05/05 2000/05/09
3 2000/05/05 2000/05/09
4 2000/05/05 2000/05/09
5 2000/05/10 2000/05/14
6 2000/05/15 2000/05/24
7 2000/05/25 null
i used RowNumber() function but i didng get any result . 我使用了RowNumber()函数,但是没有得到任何结果。 can anybody help me how to do it or even from which method or function should i perform my job .
有人可以帮我怎么做,或者我应该通过哪种方法或功能来执行我的工作? thank you
谢谢
Edited. 编辑。 note : my table has duplicate dates
注意:我的表有重复的日期
One way is to use a self-join like this: 一种方法是使用像这样的自联接:
SELECT
t1.id,
t1.DateFrom,
DATEADD(DAY,-1,t2.DateFrom) AS DateTo
FROM table1 t1
LEFT JOIN table1 t2 ON t2.id = t1.id+1
Edit: As you have duplicates, you can use a correlated subquery instead. 编辑:由于有重复项,因此可以改用相关子查询。 I've updated the SQL Fiddle to include the second solution:
我已经更新了SQL Fiddle,以包括第二个解决方案:
select
id,
DateFrom,
(
select top 1 dateadd(day,-1,datefrom)
from table1
where id > t1.id and datefrom > t1.datefrom
order by id
) as DateTo
from table1 t1
Here's an alternative using LEAD
: 这是使用
LEAD
的替代方法:
SELECT
DateFrom,
DATEADD(dd, -1, LEAD(DateFrom) OVER (ORDER BY DateFrom)) AS DateTo
FROM SomeTable;
Edit 编辑
If you want to eliminate duplicates, first pass the date data through a DISTINCT filter (eg a CTE or Derived Table). 如果要消除重复项,请首先通过DISTINCT过滤器(例如CTE或派生表)传递日期数据。
WITH cteUniqueDates AS
(
SELECT DISTINCT DateFrom
FROM SomeTable
)
SELECT
DateFrom,
DATEADD(dd, -1, LEAD(DateFrom) OVER (ORDER BY DateFrom)) AS DateTo
FROM cteUniqueDates;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.