Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

SQL:Wählen Sie den neuesten sequentiell unterschiedlichen Wert mit Gruppierung aus

Hmmm . . . Eine Methode besteht darin, den letzten Wert abzurufen. Wählen Sie dann alle letzten Zeilen mit diesem Wert aus und aggregieren Sie:

select min(rownum), colA, colB
from (select t.*,
             first_value(colA) over (partition by colB order by rownum desc) as last_colA
      from t
     ) t
where rownum > all (select t2.rownum
                    from t t2
                    where t2.colB = t.colB and t2.colA <> t.last_colA
                   )
group by colA, colB;

Oder ohne die Aggregation:

select t.*
from (select t.*,
             first_value(colA) over (partition by colB order by rownum desc) as last_colA,
             lag(colA) over (partition by colB order by rownum) as prev_clA
      from t
     ) t
where rownum > all (select t2.rownum
                    from t t2
                    where t2.colB = t.colB and t2.colA <> t.last_colA
                   ) and
      (prev_colA is null or prev_colA <> colA);

Aber in SQL Server 2008 behandeln wir das als ein Lücken-und-Inseln-Problem:

select t.*
from (select t.*,
             min(rownum) over (partition by colB, colA, (seqnum_b - seqnum_ab) ) as min_rownum_group,
             max(rownum) over (partition by colB, colA, (seqnum_b - seqnum_ab) ) as max_rownum_group
      from (select t.*,
                   row_number() over (partition by colB order by rownum) as seqnum_b,
                   row_number() over (partition by colB, colA order by rownum) as seqnum_ab,
                   max(rownum) over (partition by colB order by rownum) as max_rownum
            from t
           ) t
     ) t
where rownum = min_rownum_group and  -- first row in the group defined by adjacent colA, colB
      max_rownum_group = max_rownum  -- last group for each colB;

Dies identifiziert jede der Gruppen unter Verwendung einer Differenz von Zeilennummern. Es berechnet die maximale Rownum für die Gruppe und insgesamt in den Daten. Dies gilt auch für die letzte Gruppe.