Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a column where the first value is equal to the second value of another column?

I want to create a column where the first element is equal to the second element of another column for the same ID.The last date will be a default value.

For example, I have this table:

|ID     |start_date|
|-------|----------|
|123    |03/04/2022|
|123    |06/04/2022|
|123    |08/05/2022|
|123    |10/05/2022|
|123    |15/05/2022|
|123    |20/05/2022|

I want to get this output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

|ID     |start_date|end_date. |
|-------|----------|----------|
|123    |03/04/2022|06/04/2022|
|123    |06/04/2022|08/05/2022|
|123    |08/05/2022|10/05/2022|
|123    |10/05/2022|15/05/2022|
|123    |15/05/2022|20/05/2022|
|123    |20/05/2022|01/01/1999|

I don’t have any idea how to do it.

Thank you

>Solution :

Hi this is the query that answers your question (disregard my date format and use yours):

declare @fixeddate date
set @fixeddate='12/12/2024'
  
select Id, start_date, ISNULL(end_date, @fixeddate) end_date
from (
    select id,            
           start_date,
           lead(start_date) over (order by id) as end_date
    from test
) as t;

You can also check the fiddle i have created HERE

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading