How to repeat previous row values until another field changes - sql

I am trying to repeat a value from one row if there is no change between a column value in the row before. Thanks in advance!
create table #results (
[Floor] varchar(20)
,Room varchar(20)
,CheckInTime datetime
)
INSERT INTO #results
VALUES
('Floor1','Room1','2020-01-01 12:00:00'),
('Floor1','Room2','2020-01-05 19:00:00'),
('Floor1','Room3','2020-01-20 08:02:00'),
('Floor2','Room1','2020-01-23 19:32:00'),
('Floor1','Room1','2020-02-01 20:00:00')
And the expected result I am looking for is
in the "WantedValue" column. So if Floor is the same as the row before it, use the CheckInTime value from the row before. But this needs to carry down through multiple rows potentially.

I am interpreting the question as you want the minimum date/time every time the floor changes.
Use lag() and a cumulative sum to define the groups. Then use a window function to "spread" the minimum value:
select r.*,
min(checkintime) over (partition by grp order by checkintime) as wantedvalue
from (select r.*,
sum(case when prev_floor = floor then 0 else 1 end) over (order by checkintime) as grp
from (select r.*,
lag(floor) over (order by checkintime) as prev_floor
from results r
) r
) r
order by checkintime;
Here is a db<>fiddle.

This should wok
create table #results (
[Floor] varchar(20)
,Room varchar(20)
,CheckInTime datetime
)
INSERT INTO #results
VALUES
('Floor1','Room1','2020-01-01 12:00:00'),
('Floor1','Room2','2020-01-05 19:00:00'),
('Floor1','Room3','2020-01-20 08:02:00'),
('Floor2','Room1','2020-01-23 19:32:00'),
('Floor1','Room1','2020-02-01 20:00:00')
select
a.Floor,
a.Room,
a.CheckInTime,
b.CheckInTime
from #results a
left Join
(
select [Floor],MIN(CheckInTime) AS CheckInTime
from #results group by [Floor]
) b
ON a.[Floor]=b.[Floor]
drop table #results
Output
Floor Room CheckInTime CheckInTime
Floor1 Room1 2020-01-01 12:00:00.000 2020-01-01 12:00:00.000
Floor1 Room2 2020-01-05 19:00:00.000 2020-01-01 12:00:00.000
Floor1 Room3 2020-01-20 08:02:00.000 2020-01-01 12:00:00.000
Floor2 Room1 2020-01-23 19:32:00.000 2020-01-23 19:32:00.000
Floor1 Room1 2020-02-01 20:00:00.000 2020-01-01 12:00:00.000

Related

Date range with minimum and maximum dates from dataset having records with continuous date range

I have a dataset with id ,Status and date range of employees.
The input dataset given below are the details of one employee.
The date ranges in the records are continuous(in exact order) such that startdate of second row will be the next date of enddate of first row.
If an employee takes leave continuously for different months, then the table is storing the info with date range as separated for different months.
For example: In the input set, the employee has taken Sick leave from '16-10-2016' to '31-12-2016' and joined back on '1-1-2017'.
So there are 3 records for this item but the dates are continuous.
In the output I need this as one record as shown in the expected output dataset.
INPUT
Id Status StartDate EndDate
1 Active 1-9-2007 15-10-2016
1 Sick 16-10-2016 31-10-2016
1 Sick 1-11-2016 30-11-2016
1 Sick 1-12-2016 31-12-2016
1 Active 1-1-2017 4-2-2017
1 Unpaid 5-2-2017 9-2-2017
1 Active 10-2-2017 11-2-2017
1 Unpaid 12-2-2017 28-2-2017
1 Unpaid 1-3-2017 31-3-2017
1 Unpaid 1-4-2017 30-4-2017
1 Active 1-5-2017 13-10-2017
1 Sick 14-10-2017 11-11-2017
1 Active 12-11-2017 NULL
EXPECTED OUTPUT
Id Status StartDate EndDate
1 Active 1-9-2007 15-10-2016
1 Sick 16-10-2016 31-12-2016
1 Active 1-1-2017 4-2-2017
1 Unpaid 5-2-2017 9-2-2017
1 Active 10-2-2017 11-2-2017
1 Unpaid 12-2-2017 30-4-2017
1 Active 1-5-2017 13-10-2017
1 Sick 14-10-2017 11-11-2017
1 Active 12-11-2017 NULL
I can't take min(startdate) and max(EndDate) group by id,status because if the same employee has taken another Sick leave then that end date ('11-11-2017' in the example) will come as the End date.
can anyone help me with the query in SQL server 2014?
It suddenly hit me that this is basically a gaps and islands problem - so I've completely changed my solution.
For this solution to work, the dates does not have to be consecutive.
First, create and populate sample table (Please save us this step in your future questions):
DECLARE #T AS TABLE
(
Id int,
Status varchar(10),
StartDate date,
EndDate date
);
SET DATEFORMAT DMY; -- This is needed because how you specified your dates.
INSERT INTO #T (Id, Status, StartDate, EndDate) VALUES
(1, 'Active', '1-9-2007', '15-10-2016'),
(1, 'Sick', '16-10-2016', '31-10-2016'),
(1, 'Sick', '1-11-2016', '30-11-2016'),
(1, 'Sick', '1-12-2016', '31-12-2016'),
(1, 'Active', '1-1-2017', '4-2-2017'),
(1, 'Unpaid', '5-2-2017', '9-2-2017'),
(1, 'Active', '10-2-2017', '11-2-2017'),
(1, 'Unpaid', '12-2-2017', '28-2-2017'),
(1, 'Unpaid', '1-3-2017', '31-3-2017'),
(1, 'Unpaid', '1-4-2017', '30-4-2017'),
(1, 'Active', '1-5-2017', '13-10-2017'),
(1, 'Sick', '14-10-2017', '11-11-2017'),
(1, 'Active', '12-11-2017', NULL);
The (new) common table expression:
;WITH CTE AS
(
SELECT Id,
Status,
StartDate,
EndDate,
ROW_NUMBER() OVER(PARTITION BY Id ORDER BY StartDate)
- ROW_NUMBER() OVER(PARTITION BY Id, Status ORDER BY StartDate) As IslandId,
ROW_NUMBER() OVER(PARTITION BY Id ORDER BY StartDate DESC)
- ROW_NUMBER() OVER(PARTITION BY Id, Status ORDER BY StartDate DESC) As ReverseIslandId
FROM #T
)
The (new) query:
SELECT DISTINCT Id,
Status,
MIN(StartDate) OVER(PARTITION BY IslandId, ReverseIslandId) As StartDate,
NULLIF(MAX(ISNULL(EndDate, '9999-12-31')) OVER(PARTITION BY IslandId, ReverseIslandId), '9999-12-31') As EndDate
FROM CTE
ORDER BY StartDate
(new) Results:
Id Status StartDate EndDate
1 Active 01.09.2007 15.10.2016
1 Sick 16.10.2016 31.12.2016
1 Active 01.01.2017 04.02.2017
1 Unpaid 05.02.2017 09.02.2017
1 Active 10.02.2017 11.02.2017
1 Unpaid 12.02.2017 30.04.2017
1 Active 01.05.2017 13.10.2017
1 Sick 14.10.2017 11.11.2017
1 Active 12.11.2017 NULL
You can see a live demo on rextester.
Please note that string representation of dates in SQL should be acccording to ISO 8601 - meaning either yyyy-MM-dd or yyyyMMdd as it's unambiguous and will always be interpreted correctly by SQL Server.
It's an example of GROUPING AND WINDOW.
First you set a reset point for each Status
Sum to set a group
Then get max/min dates of each group.
;with x as
(
select Id, Status, StartDate, EndDate,
iif (lag(Status) over (order by Id, StartDate) = Status, null, 1) rst
from emp
), y as
(
select Id, Status, StartDate, EndDate,
sum(rst) over (order by Id, StartDate) grp
from x
)
select Id,
MIN(Status) as Status,
MIN(StartDate) StartDate,
MAX(EndDate) EndDate
from y
group by Id, grp
order by Id, grp
GO
Id | Status | StartDate | EndDate
-: | :----- | :------------------ | :------------------
1 | Active | 01/09/2007 00:00:00 | 15/10/2016 00:00:00
1 | Sick | 16/10/2016 00:00:00 | 31/12/2016 00:00:00
1 | Active | 01/01/2017 00:00:00 | 04/02/2017 00:00:00
1 | Unpaid | 05/02/2017 00:00:00 | 09/02/2017 00:00:00
1 | Active | 10/02/2017 00:00:00 | 11/02/2017 00:00:00
1 | Unpaid | 12/02/2017 00:00:00 | 30/04/2017 00:00:00
1 | Active | 01/05/2017 00:00:00 | 13/10/2017 00:00:00
1 | Sick | 14/10/2017 00:00:00 | 11/11/2017 00:00:00
1 | Active | 12/11/2017 00:00:00 | null
dbfiddle here
Here's an alternative answer that doesn't use LAG.
First I need to take a copy of your test data:
DECLARE #table TABLE (Id INT, [Status] VARCHAR(50), StartDate DATE, EndDate DATE);
INSERT INTO #table SELECT 1, 'Active', '20070901', '20161015';
INSERT INTO #table SELECT 1, 'Sick', '20161016', '20161031';
INSERT INTO #table SELECT 1, 'Sick', '20161101', '20161130';
INSERT INTO #table SELECT 1, 'Sick', '20161201', '20161231';
INSERT INTO #table SELECT 1, 'Active', '20170101', '20170204';
INSERT INTO #table SELECT 1, 'Unpaid', '20170205', '20170209';
INSERT INTO #table SELECT 1, 'Active', '20170210', '20170211';
INSERT INTO #table SELECT 1, 'Unpaid', '20170212', '20170228';
INSERT INTO #table SELECT 1, 'Unpaid', '20170301', '20170331';
INSERT INTO #table SELECT 1, 'Unpaid', '20170401', '20170430';
INSERT INTO #table SELECT 1, 'Active', '20170501', '20171013';
INSERT INTO #table SELECT 1, 'Sick', '20171014', '20171111';
INSERT INTO #table SELECT 1, 'Active', '20171112', NULL;
Then the query is:
WITH add_order AS (
SELECT
*,
ROW_NUMBER() OVER (ORDER BY StartDate) AS order_id
FROM
#table),
links AS (
SELECT
a1.Id,
a1.[Status],
a1.order_id,
MIN(a1.order_id) AS start_order_id,
MAX(ISNULL(a2.order_id, a1.order_id)) AS end_order_id,
MIN(a1.StartDate) AS StartDate,
MAX(ISNULL(a2.EndDate, a1.EndDate)) AS EndDate
FROM
add_order a1
LEFT JOIN add_order a2 ON a2.Id = a1.Id AND a2.[Status] = a1.[Status] AND a2.order_id = a1.order_id + 1 AND a2.StartDate = DATEADD(DAY, 1, a1.EndDate)
GROUP BY
a1.Id,
a1.[Status],
a1.order_id),
merged AS (
SELECT
l1.Id,
l1.[Status],
l1.[StartDate],
ISNULL(l2.EndDate, l1.EndDate) AS EndDate,
ROW_NUMBER() OVER (PARTITION BY l1.Id, l1.[Status], ISNULL(l2.EndDate, l1.EndDate) ORDER BY l1.order_id) AS link_id
FROM
links l1
LEFT JOIN links l2 ON l2.order_id = l1.end_order_id)
SELECT
Id,
[Status],
StartDate,
EndDate
FROM
merged
WHERE
link_id = 1
ORDER BY
StartDate;
Results are:
Id Status StartDate EndDate
1 Active 2007-09-01 2016-10-15
1 Sick 2016-10-16 2016-12-31
1 Active 2017-01-01 2017-02-04
1 Unpaid 2017-02-05 2017-02-09
1 Active 2017-02-10 2017-02-11
1 Unpaid 2017-02-12 2017-04-30
1 Active 2017-05-01 2017-10-13
1 Sick 2017-10-14 2017-11-11
1 Active 2017-11-12 NULL
How does it work? First I add a sequence number, to assist with merging contiguous rows together. Then I determine the rows that can be merged together, add a number to identify the first row in each set that can be merged, and finally pick the first rows out of the final CTE. Note that I also have to handle rows that can't be merged, hence the LEFT JOINs and ISNULL statements.
Just for interest, this is what the output from the final CTE looks like, before I filter out all but the rows with a link_id of 1:
Id Status StartDate EndDate link_id
1 Active 2007-09-01 2016-10-15 1
1 Sick 2016-10-16 2016-12-31 1
1 Sick 2016-11-01 2016-12-31 2
1 Sick 2016-12-01 2016-12-31 3
1 Active 2017-01-01 2017-02-04 1
1 Unpaid 2017-02-05 2017-02-09 1
1 Active 2017-02-10 2017-02-11 1
1 Unpaid 2017-02-12 2017-04-30 1
1 Unpaid 2017-03-01 2017-04-30 2
1 Unpaid 2017-04-01 2017-04-30 3
1 Active 2017-05-01 2017-10-13 1
1 Sick 2017-10-14 2017-11-11 1
1 Active 2017-11-12 NULL 1
You could use lag() and lead() function together to check the previous and next status
WITH CTE AS
(
select *,
COALESCE(LEAD(status) OVER(ORDER BY (select 1)), '0') Nstatus,
COALESCE(LAG(status) OVER(ORDER BY (select 1)), '0') Pstatus
from table
)
SELECT * FROM CTE
WHERE (status <> Nstatus AND status <> Pstatus) OR
(status <> Pstatus)

SQL Select: Get the previous Date in column

I have a table in my SQL server with some dates. Now I would like to create a Select which gives me a column with all dates then a second column with the previous dates of the first column and a third column with the previous dates of the previous date column(c2).
For Exempel:
c1(orginal) c2(prevoius of c1) c3(previous of c2)
2017-10-15 00:00:00 2017-04-15 00:00:00 2016-10-15 00:00:00
2017-04-15 00:00:00 2016-10-15 00:00:00 2016-04-15 00:00:00
2016-10-15 00:00:00 2016-04-15 00:00:00 2015-10-15 00:00:00
2016-04-15 00:00:00 2015-10-15 00:00:00 null
2015-10-15 00:00:00 null null
Example with colors:
Is it possible to make a SELECT where the first row would be the first date from column 1, the second from column 1 and the third from column 1. The second row would be the second date from column1, the third from column 1 and the forth from column 1.
My current query
SELECT DISTINCT(BFSSTudStichdatum) AS C1, BFSSTudStichdatum AS C2,
BFSSTudStichdatum AS C3 FROM BFSStudierende
ORDER BY C1 DESC
result:
Because you need to get a distinct list of your dates first, you will need to split your query into a common table expression and then use lag to get your c2 and c3 values:
declare #t table(c1 datetime);
insert into #t values ('2017-10-15 00:00:00'),('2017-04-15 00:00:00'),('2016-10-15 00:00:00'),('2016-04-15 00:00:00'),('2015-10-15 00:00:00')
,('2017-10-15 00:00:00'),('2017-04-15 00:00:00'),('2016-10-15 00:00:00'),('2016-04-15 00:00:00'),('2015-10-15 00:00:00');
with c as
(
select distinct c1
from #t
)
select c1
,lag(c1, 1) over (order by c1) as c2
,lag(c1, 2) over (order by c1) as c3
from c
order by c1 desc;
Output:
+-------------------------+-------------------------+-------------------------+
| c1 | c2 | c3 |
+-------------------------+-------------------------+-------------------------+
| 2017-10-15 00:00:00.000 | 2017-04-15 00:00:00.000 | 2016-10-15 00:00:00.000 |
| 2017-04-15 00:00:00.000 | 2016-10-15 00:00:00.000 | 2016-04-15 00:00:00.000 |
| 2016-10-15 00:00:00.000 | 2016-04-15 00:00:00.000 | 2015-10-15 00:00:00.000 |
| 2016-04-15 00:00:00.000 | 2015-10-15 00:00:00.000 | NULL |
| 2015-10-15 00:00:00.000 | NULL | NULL |
+-------------------------+-------------------------+-------------------------+
Are you looking for lag()?
select col1,
lag(col1, 1) over (order by col1) as col1_prev,
lag(col1, 2) over (order by col1) as col1_prev2
from t;
For SQL Server 2008 and later:
WITH DataSource AS
(
SELECT DISTINCT *
,DENSE_RANK() OVER (ORDER BY c1) rowID
FROM #t
)
SELECT DS1.[c1]
,DS2.[c1]
,DS3.[c1]
FROM DataSource DS1
LEFT JOIN DataSource DS2
ON DS1.[rowID] = DS2.[rowID] + 1
LEFT JOIN DataSource DS3
ON DS1.[rowID] = DS3.[rowID] + 2;
For SQL Server 2008 and later:
Hope you did want an auto column generation with lagging one value behind from the past columns first value. Try the following snippet.
Created a dynamic query with respect to the number of columns in the dataset.
create table BFSStudierende
(
BFSSTudStichdatum datetime
)
insert into BFSStudierende
Select getdate()
union
Select dateadd(day,1,getdate())
union
Select dateadd(day,2,getdate())
union
Select dateadd(day,3,getdate())
union
Select dateadd(day,4,getdate())
Declare #count int=(Select count(BFSSTudStichdatum ) from BFSStudierende)
Declare #query nvarchar(max)='with BFSStudierendeCte as (Select *,row_number() over(order by BFSSTudStichdatum)rn from BFSStudierende) Select *from BFSStudierendeCte as BFSStudierendeCte1'
Declare #i int=2 ;
Declare #j int ;
while(#i<=#count)
begin
Set #j=#i-1
Set #query=#query+' left outer join BFSStudierendeCte as BFSStudierendeCte'+cast(#i as varchar(5)) +' on BFSStudierendeCte1.rn+'+cast(#j as varchar(5))+'=BFSStudierendeCte'+cast(#i as varchar(5))+'.rn';
set #i+=1;
End
print #query
Execute(#query)
Note: Duplicate date will not be removed from the results. If you require duplicate to be removed. Please change the following line in the above snippet.
Declare #count int=(Select count(distinct BFSSTudStichdatum ) from BFSStudierende)
Declare #query nvarchar(max)='with BFSStudierendeCte as (Select *,row_number() over(order by BFSSTudStichdatum)rn from(Select distinct BFSSTudStichdatum from BFSStudierende)l ) Select *from BFSStudierendeCte as BFSStudierendeCte1'

How to pivot temp table in sql

Date Time Mode ID
2017-01-01 13:00:00.0000000 3 10
2017-01-01 14:00:00.0000000 1 10
2017-01-01 15:00:00.0000000 3 10
2017-01-01 15:30:00.0000000 1 10
This is a temp table.I just want to display time column as 2 columns,1 column with mode =3 and other with mode=1.
This is a temp table.I just want the below output:
Date InTime(Mode-3) OutTime(Mode-1) ID
2017-01-01 13:00:00.0000000 14:00:00.0000000 10
2017-01-01 15:00:00.0000000 15:30:00.0000000 10
Guessing you want a method to create alternating rows with fixed values (1 and 3).
you can use
case when ROW_NUMBER() over (order by [Date])%2 = 0 then 1 else 3
as the logic for your mode column
Try this,
DECLARE #TB TABLE (DATETIME VARCHAR(30),ID INT)
INSERT INTO #TB VALUES
('2017-01-01 13:00:00.0000000',10),
('2017-01-01 14:00:00.0000000',10),
('2017-01-01 15:00:00.0000000',10),
('2017-01-01 15:30:00.0000000',10 )
SELECT SUBSTRING(DATETIME,0,11) DATE
,SUBSTRING(DATETIME,12,LEN(DATETIME)) TIME
,CASE WHEN ROW_NUMBER() OVER (ORDER BY DATETIME)%2 = 0 THEN 1 ELSE 3 END MODE
,ID
FROM #TB
This works, depending on the data and datatypes/schema (and if the name of the table is timeTable):
SELECT DATE, time AS 'InTime(Mode-3)',
(SELECT TOP 1 time FROM timeTable
WHERE mode = 1
AND id = outerTable.id
AND date = outerTable.date
AND time > outerTable.time
ORDER BY date, time) AS 'OutTime(Mode-1)',
ID
FROM timeTable AS outerTable
WHERE mode = 3
the outerQuery only selects the in-times mode = 3
in innerQuery selects the next out-time, that correspondes to the selected in-time, and only returns the first one. since ordered by date and time, it should be the next one. Only tested with your given data
Output:
Date | InTime(Mode-3) | OutTime(Mode-1) | ID
---------------|---------------------|---------------------|------
2017-01-01 | 13:00:00.0000000 | 14:00:00.0000000 | 10
2017-01-01 | 15:00:00.0000000 | 15:30:00.0000000 | 10
Just for reference:
I used this table schema
CREATE TABLE timeTable(
date DATE,
time TIME,
mode INTEGER,
id INTEGER
);
Update:
With time - difference:
SELECT *, DATEDIFF(MINUTE,INTIME,OUTTIME) AS [DIFFERENCE] FROM (
SELECT [DATE], [time] AS INTIME,
(SELECT TOP 1 [time] FROM timeTable
WHERE [mode] = 1
AND [id] = outerTable.id
AND [date] = outerTable.date
AND [time] > outerTable.time
ORDER BY [date], [time]) AS OUTTIME,
[ID]
FROM [timeTable] AS outerTable
WHERE [mode] = 3
) WholeData

Contiguous Dates

Here is the table that I am working with:
MemberID MembershipStartDate MembershipEndDate
=================================================================
123 2010-01-01 00:00:00.000 2012-12-31 00:00:00.000
123 2011-01-01 00:00:00.000 2012-12-31 00:00:00.000
123 2013-05-01 00:00:00.000 2013-12-31 00:00:00.000
123 2014-01-01 00:00:00.000 2014-12-31 00:00:00.000
123 2015-01-01 00:00:00.000 2015-03-31 00:00:00.000
What I want is to create one row that shows continuous membership,
and a second row if the membership breaks by more than 2 days, with a new start and end date..
So the output I am looking for is like:
MemberID MembershipStartDate MembershipEndDate
=================================================================
123 2010-01-01 00:00:00.000 2012-12-31 00:00:00.000
123 2013-05-01 00:00:00.000 2015-03-31 00:00:00.000
There is a memberID field attached to these dates which is how they are grouped.
I've had to deal with this kind of thing before
I use something like this
USE tempdb
--Create test Data
DECLARE #Membership TABLE (MemberID int ,MembershipStartDate date,MembershipEndDate date)
INSERT #Membership
(MemberID,MembershipStartDate,MembershipEndDate)
VALUES (123,'2010-01-01','2012-12-31'),
(123,'2011-01-01','2012-12-31'),
(123,'2013-05-01','2013-12-31'),
(123,'2014-01-01','2014-12-31'),
(123,'2015-01-01','2015-03-31')
--Create a table to hold all the dates that might be turning points
DECLARE #SignificantDates Table(MemberID int, SignificantDate date, IsMember bit DEFAULT 0)
--Populate table with the start and end dates as well as the days just before and just after each period
INSERT #SignificantDates (MemberID ,SignificantDate)
SELECT MemberID, MembershipStartDate FROM #Membership
UNION
SELECT MemberID,DATEADD(day,-1,MembershipStartDate ) FROM #Membership
UNION
SELECT MemberID,MembershipEndDate FROM #Membership
UNION
SELECT MemberID,DATEADD(day,1,MembershipEndDate) FROM #Membership
--Set the is member flag for each date that is covered by a membership
UPDATE sd SET IsMember = 1
FROM #SignificantDates sd
JOIN #Membership m ON MembershipStartDate<= SignificantDate AND SignificantDate <= MembershipEndDate
--To demonstrate what we're about to do, Select all the dates and show the IsMember Flag and the previous value
SELECT sd.MemberID, sd.SignificantDate,sd.IsMember, prv.prevIsMember
FROM
#SignificantDates sd
JOIN (SELECT
MemberId,
SignificantDate,
IsMember,
Lag(IsMember,1) OVER (PARTITION BY MemberId ORDER BY SignificantDate desc) AS prevIsMember FROM #SignificantDates
) as prv
ON sd.MemberID = prv.MemberID
AND sd.SignificantDate = prv.SignificantDate
ORDER BY sd.MemberID, sd.SignificantDate
--Delete the ones where the flag is the same as the previous value
delete sd
FROM
#SignificantDates sd
JOIN (SELECT MemberId, SignificantDate,IsMember, Lag(IsMember,1) OVER (PARTITION BY MemberId ORDER BY SignificantDate) AS prevIsMember FROM #SignificantDates ) as prv
ON sd.MemberID = prv.MemberID
AND sd.SignificantDate = prv.SignificantDate
AND prv.IsMember = prv.prevIsMember
--SELECT the Start date for each period of membership and the day before the following period of non membership
SELECT
nxt.MemberId,
nxt.SignificantDate AS MembershipStartDate,
DATEADD(day,-1,nxt.NextSignificantDate) AS MembershipEndDate
FROM
(
SELECT
MemberID,
SignificantDate,
LEAd(SignificantDate,1) OVER (PARTITION BY MemberId ORDER BY SignificantDate) AS NextSignificantDate,
IsMember
FROM #SignificantDates
) nxt
WHERE nxt.IsMember = 1

Add Missing Date Range to Result Record Set

I have a table containing the working hours for the company. We define the range of the dates and the number of hours for the range.
The number of working hours which is not in the defined range is 9.5 hours.
I want to have the non-defined range with the value of 9.5 added to the result record set.
how should I make the query to get this result?
The table definition and added records:
IF OBJECT_ID ('dbo.tbl_WorkingHours') IS NOT NULL
DROP TABLE dbo.tbl_WorkingHours
GO
CREATE TABLE dbo.tbl_WorkingHours
(
Startdate DATETIME NOT NULL,
EndDate DATETIME NOT NULL,
HoursDefined FLOAT NULL,
Description VARCHAR (255) NULL,
PRIMARY KEY (Startdate,EndDate)
)
INSERT INTO dbo.tbl_WorkingHours
(Startdate,EndDate,HoursDefined,Description)
VALUES
('3/4/2010','3/29/2010',7,'')
INSERT INTO dbo.tbl_WorkingHours
(Startdate,EndDate,HoursDefined,Description)
VALUES
('5/4/2010','5/29/2010',8,'')
The Result of Select * :
Startdate | EndDate | HoursDefined | Description
----------------------------------------------------
3/4/2010 3/29/2010 7
5/4/2010 5/29/2010 8
My desired record set:
Startdate | EndDate | HoursDefined | Description
----------------------------------------------------
1/1/1900 3/3/2010 9.5
3/4/2010 3/29/2010 7
3/30/2010 5/3/2010 9.5
5/4/2010 5/29/2010 8
5/30/2010 1/1/2050 9.5
The below assumes it is not possible to have overlapping ranges or two defined ranges that are contiguous but held as separate rows.
WITH wh AS
(
SELECT Startdate, EndDate, HoursDefined, Description,
ROW_NUMBER() over (order by startdate) as rn
FROM tbl_WorkingHours
)
SELECT Startdate, EndDate, HoursDefined, Description
FROM wh
UNION ALL
SELECT ISNULL(dateadd(day,1,w1.EndDate),'19000101'),
ISNULL(dateadd(day,-1,w2.StartDate),'20500101') , 9.5 AS HoursDefined,''
FROM wh w1 FULL OUTER JOIN wh w2
ON w2.rn = w1.rn+1
ORDER BY Startdate
try something like this:
DECLARE #tbl_WorkingHours table (Startdate DATETIME NOT NULL
,EndDate DATETIME NOT NULL
,HoursDefined FLOAT NULL
,Description VARCHAR (255) NULL
,PRIMARY KEY (Startdate,EndDate)
)
INSERT INTO #tbl_WorkingHours (Startdate,EndDate,HoursDefined,Description) VALUES ('3/4/2010','3/29/2010',7,'')
INSERT INTO #tbl_WorkingHours (Startdate,EndDate,HoursDefined,Description) VALUES ('5/4/2010','5/29/2010',8,'')
;WITH OrderedRows AS
( SELECT
Startdate,EndDate,HoursDefined,Description, ROW_NUMBER() OVER (ORDER BY Startdate,EndDate) AS RowNumber
FROM #tbl_WorkingHours
)
SELECT --before rows
CONVERT(datetime,'1/1/1900') AS Startdate,ISNULL(MIN(Startdate),CONVERT(datetime,'1/2/2050'))-1 AS EndDate,9.5 AS HoursDefined, CONVERT(VARCHAR (255),'') AS Description
FROM #tbl_WorkingHours
UNION ALL
SELECT --actual rows
Startdate,EndDate,HoursDefined,Description
FROM #tbl_WorkingHours
UNION ALL
SELECT --between rows
a.EndDate+1,b.Startdate-1,9.5,''
FROM OrderedRows a
INNER JOIN OrderedRows b ON a.RowNumber=b.RowNumber-1
UNION ALL
SELECT --after rows
ISNULL(MAX(EndDate),CONVERT(datetime,'1/1/2050')) AS Startdate,CONVERT(datetime,'1/2/2050')-1 AS EndDate,9.5 AS HoursDefined, CONVERT(VARCHAR (255),'') AS Description
FROM #tbl_WorkingHours
ORDER BY Startdate,EndDate
OUTPUT:
Startdate EndDate HoursDefined Description
----------------------- ----------------------- ---------------------- -----------
1900-01-01 00:00:00.000 2010-03-03 00:00:00.000 9.5
2010-03-04 00:00:00.000 2010-03-29 00:00:00.000 7
2010-03-30 00:00:00.000 2010-05-03 00:00:00.000 9.5
2010-05-04 00:00:00.000 2010-05-29 00:00:00.000 8
2010-05-29 00:00:00.000 2050-01-01 00:00:00.000 9.5
(5 row(s) affected)