Solved

# SQL Get MIN row for each record

Posted on 2011-09-23
201 Views
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
``````
0
Question by:TechMonster
• 4
• 3

LVL 51

Expert Comment

try:

select * from (
select *, row_number() over (partition by opid order by window) rn
from myTable ) x
where rn=1
0

LVL 51

Accepted Solution

HainKurt earned 500 total points
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

Author Comment

i think that got it!  Have to test it out a few more times though...thanks.
0

Author Comment

Well it gets the min from all DATes..but I have to get the row by min dateTime for each day.
0

LVL 51

Expert Comment

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

LVL 51

Expert Comment

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

Author Comment

Perfect..thanks again
0

## Featured Post

### Suggested Solutions

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…