SQL returns the first n rows

Source: Internet
Author: User

Scenario: Returns the last 3 orders per customer.

Assuming we already have a POC index (see http://www.cnblogs.com/xiaopotian/p/6821502.html for details), there are two strategies to accomplish this: one is to use the Row_number function Another way to use the Apply operator and Offset/fetch or top is to determine which strategy is more efficient by the density of the partitioning column (CustID). Low density-means that there are a large number of different customers, each with small orders – the solution based on the Row_number function is the best.

 withC as(SelectCustid,orderdate,orderid,empid, row_number () Over(Partition byCustIDOrder  byOrderDatedesc, OrderIDdesc) asrownum fromsales.orders)Select *  fromCwhereRowNum<=3 Order  byCustid,rownum

When the partitioning column has high density-a small number of different customers, each customer has a large number of orders, with the Apply operator for each customer calls with Offset/fetch or top query

SelectC.custid,a.*  fromSales.customers asC CrossApplySelectOrderdate,orderid,empid fromSales.orders asOwhereO.custid=C.custidOrder  byOrderDatedesc, OrderIDdescOFFSET0RowsFETCHFirst3ROWS only) asA

Both of these strategies require a POC index to work well

SQL returns the first n rows

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.