T-SQL :T-SQL to Merge Consecutive startdate and Enddate of same Status or same Set of records


In some Cases we will have multiple consecutive records(Ref to  Startdate and enddate ) of same status
If we want see only one record for each status instead of many consecutive records of same status , here is the solution.

It will be nice if we explain with an example .

I have the base data in a table as follows:

BASE DATA
SUBR_NUM_ID
SUBR_NUM_CONN_KVD_TO_HOME_DIST
SUBR_NUM_CONN_KVD_PRF_START_DT
SUBR_NUM_CONN_KVD_PRF_END_DT
8847696
-1
01/01/1600
31/01/2013
8847696
-1
01/02/2013
28/02/2013
8847696
-1
01/03/2013
31/03/2013
8847696
6892
01/04/2013
30/04/2013
8847696
-1
01/05/2013
31/05/2013
8847696
-1
01/06/2013
31/12/9999


I want to consolidate it as follows:

MERGED DATA
SUBR_NUM_ID
SUBR_NUM_CONN_KVD_TO_HOME_DIST
SUBR_NUM_CONN_KVD_PRF_START_DT
SUBR_NUM_CONN_KVD_PRF_END_DT
8847696
-1
01/01/1600
31/03/2013
8847696
6892
01/04/2013
30/04/2013
8847696
-1
01/05/2013
31/12/9999



This will work in SQL server

  WITH group_assigned_data AS
  ( SELECT
        SUBR_NUM_ID
      , SUBR_NUM_CONN_KVD_TO_HOME_DIST
      , SUBR_NUM_CONN_KVD_PRF_START_DT
      , SUBR_NUM_CONN_KVD_PRF_END_DT
      , ROW_NUMBER() OVER( PARTITION BY SUBR_NUM_ID ,SUBR_NUM_CONN_KVD_TO_HOME_DIST  ORDER BY SUBR_NUM_CONN_KVD_PRF_START_DT ) AS status_sequence_id
      , ROW_NUMBER() OVER (                             ORDER BY SUBR_NUM_CONN_KVD_PRF_START_DT) AS sequence_id
    FROM
        ODS_Schema.TestMergedate AS t )
     
  SELECT
         SUBR_NUM_ID
      , SUBR_NUM_CONN_KVD_TO_HOME_DIST
   , MIN(SUBR_NUM_CONN_KVD_PRF_START_DT)   AS SUBR_NUM_CONN_KVD_PRF_START_DT,
    MAX(SUBR_NUM_CONN_KVD_PRF_END_DT)   AS SUBR_NUM_CONN_KVD_PRF_END_DT
  FROM
    group_assigned_data
  GROUP BY
      SUBR_NUM_ID
      , SUBR_NUM_CONN_KVD_TO_HOME_DIST,
    sequence_id - status_sequence_id
   Order by SUBR_NUM_CONN_KVD_PRF_START_DT


  

Comments

Popular posts from this blog

SSAS : A connection cannot be made to redirector. Ensure that 'SQL Browser' service is running. (Microsoft.AnalysisServices.AdomdClient). + Solution

SSIS Error : Unable to infer the XSD from the XML file. The XML contains multiple namespaces