2015-12-03 74 views
0

前3最大值我歸類爲降序即如何選擇從SQL Server列

id Count OR  id Count OR  id Count 
1 4    1 5    1 11 
2 4    2 2    2 1 
3 4    3 1    3 1 
4 4    4 1    4 1 
5 4    5 1    5 1 

現在我要選擇前3最大值在SQL Server中派生列值。我該如何選擇,以便每次查詢返回一致的結果。
例如,如果Count的值相同,其中id應該返回爲前3個最大值,類似地,如果第3個值與其他值匹配並且如果第2個值與其他值匹配,那麼應該返回哪個id查詢。每次執行查詢時結果都應該一致。

回答

1

的與頂級功能的關係參數將返回所有匹配的頂值這行:,

select top (3) with ties id, count from table1 
order by count desc 

另外,如果你想只返回3個值,但要確保他們總是相同的3個值,那麼你將需要使用別的東西作爲決勝盤。在這種情況下,它看起來像您的ID列可能是唯一的。

select top (3) id, count from table1 
order by count desc, id