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

Create end date based on max date within partition?

I have a database table labeled "Transactions," and it lacks an end date. I need to create an end date for date diff formulas in tableau.
DB table name = [pursuant].[dbo].[transactions]

Each record = a landlord with a status column and date that status started. Example: row 1 has landownerA with "Passed to Agent" status on 1/1/24. row 2 has landownerA with "Outreach" status on 1/22/24.

I need to create and end date based on [Date] column in table.

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

I want to turn this table into this:

enter image description here

Here is the code I tried using, but it’s erroring out:

  select Landowner, Status, min(Date), max(Date)
from (select Transactions.*, row_number() over (partition by Landowner, status order by 
Date) as seqnum
  from Transactions t
 ) t
group by Landowner, Status, dateadd(day, - seqnum, Date)
order by Landowner, min(Date);

>Solution :

You can use a windowed LEAD() function to look ahead to the next start date for a given landowner, DATEADD() to subtract a day, and ISNULL() to handle to "no value" case.

Something like:

SELECT
    T.LandOwner,
    T.Comments,
    T.Status,
    T.Agent,
    T.Date as StartDate,
    ISNULL(
        DATEADD(day, -1,
            LEAD(T.Date) OVER(PARTITION BY T.LandOwner ORDER BY T.Date)
            ), 
        CONVERT(DATE, GETDATE())
    ) AS EndDate
FROM pursuant.dbo.Transactions T

Results:

LandOwner Comments Status Agent StartDate EndDate
85 Wilmigton LLC Test 1 Passed to Agent Mike 2024-01-05 2024-01-21
85 Wilmigton LLC Test 2 Outreach Mike 2024-01-22 2024-02-28
Abe Holdings II LLC Test 1 Passed to Agent Dan 2024-01-08 2024-01-24
Abe Holdings II LLC Test 2 Outreach Dan 2024-01-25 2024-02-28

See this dv<>fiddle for a demo.

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