Skip to content
Advertisement

SQL Union as Subquery to create Date Ranges from Start Date

I have three tabels, each of them has a date column (the date column is an INT field and needs to stay that way). I need a UNION accross all three tables so that I get the list of unique dates in accending order like this:

Then I need to add a column to the result of the query where I subtract one from each date and place it one row above as the end date. Basically I need to generate the end date from the start date somehow and this is what I got so far (not working):

Thanks a lot for your help!

Advertisement

Answer

Building on your existing union cte, we can use lead() in the outer query to get the start_date of the next record, and withdraw 1 from it.

If the datatype the original columns are numeric, then you need to do some casting before applying date functions:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement