Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Regroupez des objets similaires dans différentes plages de dates pour obtenir des dates minimales et maximales dans SQL Server

Cela devrait vous aider :

CREATE TABLE Account (AccountID bigint,
                      onln_status varchar(3),
                      BrowseStatus char(1),
                      Beg_date date,
                      End_Date date);
GO

INSERT INTO Account
SELECT A, O, B, CONVERT(date,S,101), CONVERT(date,E,101)
FROM (
    VALUES (123456789,'On','Y','1/1/2018','2/1/2018'),
           (123456789,'On','N','2/2/2018','4/1/2018'),
           (123456789,'On','Y','4/2/2018','5/1/2018'),
           (123456789,'Off','N','5/2/2018','7/1/2018'),
           (123456789,'Off','Y','7/2/2018','8/1/2018'),
           (123456789,'On','Y','8/2/2018','10/1/2018'),
           (123456789,'On','N','10/2/2018','11/1/2018')) V(A, O, B, S, E);
GO

WITH Grps AS(
    SELECT *,
           ROW_NUMBER() OVER (ORDER BY Beg_date) - --You may need to add a PARTITION here (I.e. on AccountID)
           ROW_NUMBER() OVER (PARTITION BY onln_status ORDER BY Beg_date) AS Grp --You may need to add a PARTITION here (I.e. on AccountID)
    FROM Account)
SELECT AccountID,
       onln_status,
       MIN(beg_date) AS beg_date,
       MAX(End_date) AS End_Date
FROM Grps
GROUP BY AccountID,
          onln_status,
          Grp;

GO
DROP TABLE Account;

Notez mes commentaires sur l'utilisation de ROW_NUMBER() pourtant. Vous devrez peut-être ajouter d'autres partitions.