This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Check the below input data and expected output to generate the report on range basis on the common combination of SendFlag and ReceiveFlag.
Input Data:
1 2 3 4 5 6 7 8 9 10 |
ID CreationDate SendFlag ReceiveFlag ----------- ------------ -------- ----------- 1 2016-08-08 0 0 2 2016-10-01 0 0 3 2016-11-26 1 0 4 2016-12-26 1 0 5 2017-01-08 1 0 6 2017-03-10 1 1 7 2017-06-20 1 1 8 2017-08-15 0 1 |
Expected Output:
1 2 3 4 5 6 |
StartID EndID SendFlag ReceiveFlag ----------- ----------- -------- ----------- 1 2 0 0 3 5 1 0 6 7 1 1 8 8 0 1 |
Create a table with sample data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
CREATE TABLE Flags ( ID INT ,CreationDate DATE ,SendFlag BIT ,ReceiveFlag BIT ) GO INSERT INTO Flags VALUES (1,'20160808',0,0) ,(2,'20161001',0,0) ,(3,'20161126',1,0) ,(4,'20161226',1,0) ,(5,'20170108',1,0) ,(6,'20170310',1,1) ,(7,'20170620',1,1) ,(8,'20170815',0,1) GO |
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
;WITH CTE1 AS ( SELECT f.*, ROW_NUMBER() OVER (ORDER BY f.ID) rnk FROM Flags f left JOIN Flags f2 on f.id + 1 = f2.id and f.SendFlag = f2.SendFlag and f.ReceiveFlag = f2.ReceiveFlag WHERE f2.ID IS NULL ), CTE2 AS ( SELECT f2.*,ROW_NUMBER() OVER (ORDER BY f2.ID) rnk FROM Flags f RIGHT JOIN Flags f2 on f.id = f2.id - 1 and f.SendFlag = f2.SendFlag and f.ReceiveFlag = f2.ReceiveFlag WHERE f.ID IS NULL ) SELECT c2.ID as StartID,c1.ID as EndID,c1.SendFlag,c2.ReceiveFlag FROM CTE1 c1 INNER JOIN CTE2 c2 on c1.rnk = c2.rnk |
Please try the different solution for this puzzle and share it via comment...