SQL to find the first occurrence of sets of data in a table

前端 未结 4 1442
执念已碎
执念已碎 2021-02-09 14:48

Say if I have a table:

CREATE TABLE T
(
    TableDTM  TIMESTAMP  NOT NULL,
    Code      INT        NOT NULL
);

And I insert some rows:

4条回答
  •  终归单人心
    2021-02-09 15:11

    Try this:

    SELECT MIN(TableDTM) TableDTM, Code
    FROM
    (
        SELECT T1.TableDTM, T1.Code, MIN(T2.TableDTM) XTableDTM
        FROM T T1
        LEFT JOIN T T2
        ON T1.TableDTM <= T2.TableDTM
        AND T1.Code <> T2.Code
        GROUP BY T1.TableDTM, T1.Code
    ) X
    GROUP BY XTableDTM, Code
    ORDER BY 1;
    

提交回复
热议问题