How to get minimum date by each records from multiple records

后端 未结 2 1211
长发绾君心
长发绾君心 2021-01-28 05:14

I would like to get the minimum date of each record in my table having multiple entry of date with one primary key. Take a look at my table:

   CaseNo     Entry_         


        
2条回答
  •  长情又很酷
    2021-01-28 05:40

    Unsure what RDBMS you're using, but two approaches come to mind.

    JOIN against derived table

    Create a derived table of (CaseNo, MIN(Entry_date)) rows, and join that against your primary table:

        SELECT CaseNo, Entry_date, d.Min_date AS "Min_date"
          FROM tbl
    INNER JOIN (  SELECT CaseNo, MIN(Entry_date) AS "Min_date"
                    FROM tbl
                GROUP BY 1) d
            ON tbl.CaseNo = d.CaseNo;
    

    Use analytic (window) functions

    If your RDBMS supports it, you can skip the derived table and ask for your records with the minimum Entry_date by CaseNo provided by the system:

    SELECT CaseNo, Entry_date, MIN(Entry_date) OVER (PARTITION BY CaseNo) AS "Min_date"
      FROM tbl;
    

提交回复
热议问题