How to get minimum date by each records from multiple records

后端 未结 2 1212
长发绾君心
长发绾君心 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:37

    try this

    SELECT
      CaseNo,
      Entry_date,
      (SELECT MIN(Entry_date) FROM Cases subc WHERE subc.CaseNo=c.CaseNo GROUP BY CaseNo) AS MinEntryDate
    FROM Cases c
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题