Select distinct from usercolumn and minimum value of dates for each field in usercolumn

nasiry picture nasiry · Jun 20, 2009 · Viewed 23.2k times · Source

I have some data like this but more than 1500000 records and more than 700 users:

usercolumn   ,       datecolumn\     
a1            ,      1998/2/11\
a2            ,      1998/3/11\
a1            ,      1998/2/15\
a4            ,      1998/4/14\
a3            ,      1999/1/15\
a2            ,      1998/11/12\
a2            ,      1999/2/11\
a3            ,      2000/2/9\
a1            ,      1998/6/5\
a3            ,      1998/7/7\
a1            ,      1998/3/11\
a5            ,      1998/3/18\
a2            ,      1998/2/8\
a1            ,      1998/12/11\
a4            ,      1998/12/1\
a5            ,      1998/2/11\
....

I would like to have distinct data from usercolumn and minimum value of date for each user like this:

usercolumn      ,    datecolumn \        
a1              ,    1998/2/11\
a2              ,    1998/2/8\
a3              ,    1998/7/7\
a4              ,    1998/4/14\
a5              ,    1998/2/11\
....

please help me to write an SQL command to do this for oledb adapter in c#, thanks.

Answer

brian-brazil picture brian-brazil · Jun 20, 2009
SELECT usercolumn, MIN(datecolumn) FROM tablename GROUP BY usercolumn;

Note that if you want other columns they must either appear in the GROUP BY clause or be constant across rows. Otherwise the result will be non-deterministic.