Author |
Topic |
hai
Yak Posting Veteran
84 Posts |
Posted - 2008-03-11 : 15:36:17
|
Declare @myTable table (cat varchar(100), subcat varchar(100), rank int ) Insert Into @myTable Select 'A', 'a', 2 Union All Select 'A', 'b', 52 Union All Select 'A', 'c', 14 Union All Select 'A', 'd', 46 Union All Select 'A', 'e', 37 Union All Select 'A', 'f', 95 Union All Select 'A', 'g', 73 Union All Select 'A', 'h', 67 Union All Select 'A', 'i', 80 Union All Select 'A', 'j', 03 Union All Select 'B', 'a', 18 Union All Select 'B', 'b', 44 Union All Select 'B', 'c', 52 Union All Select 'B', 'd', 37 Union All Select 'B', 'e', 28 Union All Select 'B', 'f', 06 Union All Select 'B', 'g', 14 Union All Select 'B', 'h', 90 Union All Select 'B', 'i', 2 Union All Select 'B', 'j', 31 declare @n int Set @n = 5 Select Cat, subCat, rank From @myTable as A Where (Select count(1) From @myTable Where cat=A.cat and rank <= A.rank)<=@n Order By Cat, Rank Desc This will get the top 5 rows...[url]http://weblogs.sqlteam.com/mladenp/archive/2005/08/01/7421.aspx[/url]What can I do to get the top 3 with rank in (37,14,2) and that the count must be 3 or greater.Thanks... |
|
spirit1
Cybernetic Yak Master
11752 Posts |
Posted - 2008-03-11 : 16:07:56
|
emmm... you mean like this?Set @n = 3Select Cat, subCat, rankFrom @myTable as AWhere (Select count(1) From @myTable Where cat=A.cat and rank <= A.rank)<=@nand rank in (37,14,2)Order By Cat, Rank Desc _______________________________________________Causing trouble since 1980blog: http://weblogs.sqlteam.com/mladenpSSMS Add-in that does a few things: www.ssmstoolspack.com |
 |
|
hai
Yak Posting Veteran
84 Posts |
Posted - 2008-03-11 : 16:23:26
|
Spirit...your query return:Cat subCat rankA c 14A a 2B g 14B i 2What I really want is this:Cat subCat rankA e 37A c 14A a 2B d 37B g 14B i 2I think I figure this thing out from your query....thanks |
 |
|
spirit1
Cybernetic Yak Master
11752 Posts |
Posted - 2008-03-11 : 16:33:31
|
select Cat, subCat, rankfrom (select Cat, subCat, rankfrom @myTablewhere rank in (37,14,2)) Awhere (Select count(1) From @myTable Where rank in (37,14,2) and cat=A.cat and rank <= A.rank)<=@nOrder By Cat, Rank Desc_______________________________________________Causing trouble since 1980blog: http://weblogs.sqlteam.com/mladenpSSMS Add-in that does a few things: www.ssmstoolspack.com |
 |
|
|
|
|