SQL Get MIN row for each record

Hello I have the following table data(posed in the CODE sec.  

wondering how to get the row data with the min date from each OPID.  If the 2nd Window date is less than 1st Window date then the 2nd Window should be read.    

get the min date goes something like...
Select distinct min DATE, OPID, Window
from TABLE

But the problem is if the 2nd window is the lesser date of the windows.
Accnt	OPID	DATE	Window 
34	1	9/22/11 12:32 PM	1st WINDOW
34	1	9/22/11 12:33 PM	2nd WINDOW
12	2	9/21/11 11:02 AM	1st WINDOW
12	2	9/21/11 11:01 AM	2nd Window
455	1	9/22/11 1:09pm	1st WINDOW

Open in new window

TechMonsterAsked:
Who is Participating?
 
HainKurtConnect With a Mentor Sr. System AnalystCommented:
oops, we should sue [DATE]

select * from (
select *, row_number() over (partition by opid order by [DATE]) rn
from myTable ) x
where rn=1
0
 
HainKurtSr. System AnalystCommented:
try:

select * from (
select *, row_number() over (partition by opid order by window) rn
from myTable ) x
where rn=1
0
 
TechMonsterAuthor Commented:
i think that got it!  Have to test it out a few more times though...thanks.
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
TechMonsterAuthor Commented:
Well it gets the min from all DATes..but I have to get the row by min dateTime for each day.
0
 
HainKurtSr. System AnalystCommented:
then you should partition by day & opid

easy way is to get date part

select floor(cast(GETDATE() as float))

select * from (
select *, row_number() over (partition by opid,  floor(cast([DATE] as float)) order by [DATE]) rn
from myTable ) x
where rn=1
0
 
HainKurtSr. System AnalystCommented:
or use CONVERT(varchar, getdate(), 101) -- to get rid of time part and group by date only like : 09/23/2011

select * from (
select *, row_number() over (partition by opid, CONVERT(varchar, getdate(), 101) order by [DATE]) rn
from myTable ) x
where rn=1
0
 
TechMonsterAuthor Commented:
Perfect..thanks again
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.