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 |
|
loppis99
Starting Member
6 Posts |
Posted - 2007-09-20 : 07:31:16
|
| Hi,I'm trying to select the two best scores for every item in a table, but i need help with the SQL query.The table is like thisItem ScoreAA 100AA 110AA 130BB 100BB 120BB 140So i want the result like thisItem ScoreAA 130 AA 110BB 140BB 120Thanks for any help |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2007-09-20 : 07:51:48
|
| If you're using SQL 2005 you can use the RANK() functionDECLARE @yourtable TABLE (item char(2),Score int)INSERT INTO @yourtableSELECT'AA', 100UNION allSELECT'AA', 110UNION allSELECT'AA', 130UNION allSELECT'BB', 100UNION allSELECT'BB', 120UNION allSELECT'BB', 140SELECT Item,Score,aRankFROM( select Item,Score,'aRank' = RANK() OVER(PARTITION BY item order by score) from @yourtable) aWHERE aRank <=2Jim |
 |
|
|
nr
SQLTeam MVY
12543 Posts |
Posted - 2007-09-20 : 07:52:28
|
| select Item, max(Score) from tbl t1 group by Itemunion allselect Item, max(score) from tbl t1where score not in (select max(t2.Score) from tbl t2 where t1.item = t2.item)==========================================Cursors are useful if you don't know sql.DTS can be used in a similar way.Beer is not cold and it isn't fizzy. |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2007-09-20 : 08:48:40
|
Not testedselect item,scorefrom( select item,score, row_number() over (partition by item order by score desc) as row_num from your_table) as Twhere row_num<=2 MadhivananFailing to plan is Planning to fail |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
|
|
loppis99
Starting Member
6 Posts |
Posted - 2007-09-20 : 09:29:46
|
Thanks, using SQL 2005 and all examples works, but it says, that the OVER statment is not supported, but the result is ok |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2007-09-20 : 09:32:11
|
quote: Originally posted by loppis99 Thanks, using SQL 2005 and all examples works, but it says, that the OVER statment is not supported, but the result is ok 
Did you run it in SQL Server 2005?MadhivananFailing to plan is Planning to fail |
 |
|
|
loppis99
Starting Member
6 Posts |
Posted - 2007-09-20 : 11:03:49
|
| I tested it in a view in SQL 2005 |
 |
|
|
|
|
|
|
|