Sorting in Oracle Groupings (rank function)

Source: Internet
Author: User

Demand:

Find out how many top50 each vendor sells in each type of product

Analysis:

1. Query, GROUP by the specified field (vendor, product type), take the first 50 rows of each group, and view the number of each vendor

2. Use the Rank function to rank the sales of each vendor, each type of product, and add a fake ran

3. Filter the rows with the ran less than or equal to 50, group by vendor, product type, Count

Sql:

SelectGyscode Vendor code, typeid type ID,Count(1) Num from(SelectT.gyscode, T.typeid,sum(T.sale) sale, rank () Over (partition by T.gyscode, T.typeid ORDER by sum (B.sale) desc ) ran fromT_sale Twhere         --Calculation period: 1 to last monthT.log_date>=Add_months (Trunc (Sysdate,'mm'),-1)        andT.log_date<=Last_day (Add_months (Trunc (Sysdate,'mm'),-1))          Group  byT.gyscode, T.typeid)
Where ran <=Group byGyscode, typeID

Note: There are two uses of the Runk function:

Dense_rank: Consecutive rankings, if there are two vendors of the same sales, ranked the same, but the next supplier ranked +1

Rank: non-sequential ranking, if there are two vendors of the same sales, ranked the same, but the next supplier ranked +2 (2: The number of vendors with the same sales)

The Runk function is ranked in two ways:

1. Rank all results (no partition, equivalent to rownum sorted by a field)

2. Group ranking (plus partition)

Sorting in Oracle Groupings (rank function)

Related Article

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.