Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 HAVING clause befuddlement

Author  Topic 

glt101
Starting Member

28 Posts

Posted - 2010-08-12 : 18:11:44
Hi All,

I have run into this a couple of times and never found a simple solution.

In a table with three columns
ID int (always unique)
SN char(7)
Version float

There may be many entries of a given SN with differing values of
Version. There may also be many different values of SN.
One set of rows for a given SN might look like:

ID, SN, Version
100, 987687, 1.0
150, 987687, 1.1
204, 987687, 2.0
1032, 987687, 3.5

How do I return a results set that lists only SNs that have the
maximum value of Version for that particular SN? I tried using
a GROUP BY clause and adding HAVING Version = MAX(Version)
but unsurprisingly that doesn't work.

Sorry if this is an FAQ.
Cheers,
Geoff

dmilam
Posting Yak Master

185 Posts

Posted - 2010-08-12 : 18:33:15
Have you tried SELECT MAX(Version) instead?
Go to Top of Page

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2010-08-12 : 18:41:02
[code]SELECT *
FROM (SELECT *, rec_id = ROW_NUMBER() OVER(PARTITION BY SN ORDER BY Version DESC)
FROM table_name) D
WHERE rec_id = 1;[/code]

Go to Top of Page

dmilam
Posting Yak Master

185 Posts

Posted - 2010-08-12 : 19:09:17
You'll need to use OVER

SELECT *
FROM (SELECT *, rec_id = ROW_NUMBER() OVER (PARTITION BY SN ORDER BY VERSION DESC)
FROM @test) D
WHERE rec_id = 1
Go to Top of Page

glt101
Starting Member

28 Posts

Posted - 2010-08-13 : 09:55:55
Hi Guys,

Thanks for the replies.

Hmmm. OVER clause.

Definition for anyone following on behind:
http://msdn.microsoft.com/en-us/library/ms189461.aspx

A new on on me. I'll give it a shot.

Cheers,
Geoff
Go to Top of Page
   

- Advertisement -