Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Raggruppa oggetti simili in intervalli di date diversi per ottenere date minime e massime in SQL Server

Questo dovrebbe farti andare avanti:

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;

Nota i miei commenti sull'uso di ROW_NUMBER() anche se. Potrebbe essere necessario aggiungere altre partizioni.