How to get minimum date by each records from multi

2019-03-03 20:19发布

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_date   
   ABC-001     2/12/13
   ABC-002     2/09/13
   ABC-001     1/01/13
   ABC-001     1/31/13
   ABC-002     1/01/13
   ABC-003     2/01/12
   ABC-003     2/18/13

I want to have this result:

       CaseNo     Entry_date    Min_date
       ABC-001     2/12/13      1/01/13
       ABC-002     2/09/13      1/09/13
       ABC-001     1/01/13      1/01/13
       ABC-001     1/31/13      1/01/13
       ABC-002     1/09/13      1/09/13 
       ABC-003     2/01/12      2/01/13
       ABC-003     2/18/13      2/01/13

I want to get the minimum date of each CaseNo recorded on my table.

I tried this code:

Select CaseNo,Entry_date, Min(Entry_date) as Min_date
from mytable group by CaseNo

Result is this:

   CaseNo     Entry_date    Min_date
   ABC-001     1/01/13      1/01/13
   ABC-002     1/09/13      1/09/13 
   ABC-003     2/01/12      2/01/13

The code remove the row not having the minimum date. I want to display all records with their minimum date as Min_date.

2条回答
老娘就宠你
2楼-- · 2019-03-03 20:33

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;
查看更多
迷人小祖宗
3楼-- · 2019-03-03 20:45

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
查看更多
登录 后发表回答