Rank by SQL

Source: Internet
Author: User

In many cases, we need statistics on the ranking, the most common is the score, the number of votes, and so on. However, before SQL Server 2005, SQL Server 2000 did not provide this direct function for us to use. The same is true for access.

Access:

 
Select name, score, (select IIF (isnull (sum (1), 1, sum (1) + 1) from score_rank where score>. score) as rank from score_rank a order by score DESC

Web SQL 2000:

 
Select name, score, (select isnull (sum (1), 0) + 1 from score_rank where score> A. Score) as rank from score_rank a order by score DESC

Web SQL 2005:

 
Select name, score, rank () over (order by score DESC) as [Rank], dense_rank () over (order by score DESC) as [rank1], ntile (4) over (order by score DESC) as [rank2] From score_rank order by score DESC;

Use of select sum (1)
Select count (*) returns the number of all records that meet the condition, which is the same as select sum (1)
However, sum () can be used to transmit any number, either a negative number or a floating point number. The returned value is the input value n * Number of records meeting the conditions. m is simply understood as the number of rows * 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.