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.
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: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
byCaseNo
provided by the system:try this