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.
| Author |
Topic |
|
JJ297
Aged Yak Warrior
940 Posts |
Posted - 2011-04-22 : 14:51:22
|
This stored procedure select area, max(maxseqnum) as maxseqnum, loc, clms from test1group by clms, area, locproduces this table:Area Maxseqnum Loc clms02 0 FieldOffice 21545802 3 Fieldoffice 54329802 4 DDS 54329802 4 FieldOffice 65829802 5 DDS 65829802 8 Fieldoffice 21729802 9 DDS 217298 I want to get this instead by showing only one clms with the highest maxseqnumArea Maxseqnum Loc clms02 0 FieldOffice 21545802 4 DDS 54329802 5 DDS 65829802 9 DDS 217298 Here's the table info. Thanks so much!CREATE TABLE [dbo].[test1]( [area] [varchar](2) NULL, [maxseqnum] [smallint] NULL, [loc] [varchar](50) NULL, [clms] [char](6) NOT NULL, ) ON [PRIMARY]GOInsert into test1Select '02', ' ', 'Fieldoffice', '215458' union allSelect '02', '3', 'Fieldoffice', '543298' union allSelect '02', '4', 'DDS', '543298' union allSelect '02', '4', 'Fieldoffice', '658298' union allSelect '02', '5', 'DDS', '658298' union allSelect '02', '8', 'Fieldoffice', '217298' union allSelect '02', '9', 'DDS', '217298' |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2011-04-22 : 15:04:07
|
| SELECT *FROM( select area,maxseqnum,loc,clms,row_number() over(partition by area,clms order by maxseqnum desc) as rownfrom #test1) t1WHERE rown = 1ORDER BY area,maxseqnumJimEveryday I learn something that somebody else already knew |
 |
|
|
JJ297
Aged Yak Warrior
940 Posts |
Posted - 2011-04-22 : 15:07:51
|
| Thanks Jim!!!! Please explain so I will know how to do this the next time I've been stuck all day. What's the over(partition etc... means? |
 |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2011-04-22 : 15:17:20
|
| Row_Number() is a windowed function ( rank() is another popular one) that says"assign row numbers to the groups of area,clms that ordered by the maxseqnum desc", so that the biggest maxseqnum gets a value of 1, the next biggest 2, etc. In your example, change the are in the last two records to '03' and see what that does, it may help you see better what the row_number() is doing.JimEveryday I learn something that somebody else already knew |
 |
|
|
JJ297
Aged Yak Warrior
940 Posts |
Posted - 2011-04-22 : 15:59:17
|
| Wow thanks so much for explaning to me I will read up further on it. I added more fields to it and it's running slower any way to speed it up? |
 |
|
|
|
|
|
|
|