I have a table of data. I have a field which shows date. I had set this column as Start Date. I want to create an additional column as End Date, where the End Date will be the Start Date of the next row. Can you give me a query of creating the End Date by taking the data of the Start Date in next row ?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
First of all, you have to come up with a definition of "order", since rows in a table are stored without any order.
When you know what your order is, you can create a stored procedure that goes:
I'm assuming that you currently have rows with values such as
And you want to change to
Quite apart from the redundancy and maintenance issue that reminds me of this question where such a setup with correlated columns actually caused the original poster problems when querying data. (I prefer Unreason's answer to my own on that question!)
Why do you need to add the
EndDate
column? It will probably be possible to come up with a query that works without it.Edit After much faffing about with
row_number()
I actually couldn't find a query with a better plan than this. (Assumes index onStartDate
)I'm answering this question because it is being referenced somewhere else.
Depending on the
id
having no holes is dangerous.identity
columns can have gaps which the currently accepted answer does not take into account.In SQL Server 2012+, the answer is simply
lag()
. In earlier versions, you can usecross apply
:With an index on
table(StartDate)
, this might even have reasonable performance.What about last row? The endDate will be blank for that?
Assuming you already have your columns and that you have an Auto-Incrementing Primary Key:
Depends on what you mean by "next" row.
Can you provide sample dataset, and specify how you determine what order the rows go in?
EDIT
Your record order really does matter -- you're going to have to determine what that is. For now, I'm working off of the assumption that ordering it by start_date is acceptable.