Friday, 7 August 2015

Complex SQL Scenario

Get the minimum date if the consecutive code is same

CT KBB(DT DATE,COD VARCHAR(1))
INS INTO KBB VALUES('2014-01-01','A');
INS INTO KBB VALUES('2014-01-02','A');
INS INTO KBB VALUES('2014-01-03','D');
INS INTO KBB VALUES('2014-01-04','A');
INS INTO KBB VALUES('2014-01-05','D');
INS INTO KBB VALUES('2014-01-06','A');

Solution:
SEL EFF_DT,COD,
RANK() OVER(ORDER BY EFF_DT RESET WHEN COD<>MAX(COD) 
OVER(ORDER BY EFF_DT ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING))

FROM KBB

1 comment:

  1. can u pls explain in detail , for above query ..
    1 preceeding and rank over is abit confusing.

    ReplyDelete