Do you really play with SQL? Top and apply

Source: Internet
Author: User

Can you really play with SQL? Top and apply

This chapter would like to write some basic usage of top and apply, but it doesn't seem to make any sense, so delete some useless things, leaving only a few examples to ensure the integrity of the series.

Top and apply solve common problems, such as returning 3 most recent orders for each employee, the higher the order time priority, but also need to introduce a winning attribute to determine the order priority of the timeframe, such as the available ID as the winning attribute. The solution provided here is much simpler and faster to execute than other scenarios.

Return 3 latest orders for each employee:

SELECTempid, OrderID, CustID, OrderDate, RequiredDate fromSales.orders asO1WHEREOrderIDinch(SELECT TOP 3OrderID fromSales.orders asO2WHEREO2.empid=O1.empidORDER  byOrderDateDESC, OrderIDDESC)

Apply apply to solve:

SELECTe.empid, A.orderid, A.custid, A.orderdate, A.requireddate fromHr.employees ase CrossAPPLY (SELECT TOP 3OrderID, CustID, order Date, RequiredDate fromSales.orders asoWHEREO.empid=E.empidORDER  byOrderDateDESC, OrderIDDESC                    )  asA

Scan employees first to get Empid, and the Orders table query for each EMPID value returns the 3 most recent orders for that employee. You can return multiple properties here.

There is also a solution that is faster than using the Apply operator in a specific case, using the Row_number function. Calculate line numbers for each order, partition by Empid, and sort by orderdate DESC, OrderID desc order. Then, in an external query, only rows with row numbers less than or equal to 3 are filtered.

As follows:

SELECTOrderID, CustID, OrderDate, RequiredDate from(SELECTOrderID, CustID, OrderDate, RequiredDate, Row_number () Over(PARTITION byEmpidORDER  byOrderDateDESC, OrderIDDESC) asrownum fromsales.orders) asDWHERERowNum<= 3 

Practice:

Select the first num name of the corresponding class from the student table

--Show Results /* BJ         XH   name       CJ-----------------------------------class         A006 A6         1001 class         A005 A5         991 class         A001 A1         891 class         A002 A2         892 classes         B001 B7         1002 Classes         B001 B6         992 classes         B001 B9         Class 972         B001 B8         902 class         B001 B5         * *

--Create a test tableDeclare @student Table(---Student Tablebjvarchar(Ten),--classXhChar(4),--School NumberNamevarchar(Ten),--nameCjint)--Achievements  Declare @tj Table(---Statisticsbjvarchar(Ten),--classNumint)--Number of Students: Select the first num name of the corresponding class from the student table SetNocount on --Add test DataInsert @student Select 'Class One','A001','A1', theInsert @student Select 'Class One','A002','A2', theInsert @student Select 'Class One','A003','A3', -Insert @student Select 'Class One','A004','A4', theInsert @student Select 'Class One','A005','A5', AboutInsert @student Select 'Class One','A006','A6', -Insert @student Select 'Class One','A007','A7', the Insert @student Select 'Class Two','B001','B1', +Insert @student Select 'Class Two','B001','B2',BayiInsert @student Select 'Class Two','B001','B3', theInsert @student Select 'Class Two','B001','B4', theInsert @student Select 'Class Two','B001','B5', theInsert @student Select 'Class Two','B001','B6', AboutInsert @student Select 'Class Two','B001','B7', -Insert @student Select 'Class Two','B001','B8', -Insert @student Select 'Class Two','B001','B9', the   Insert @tj Select 'Class One',3Insert @tj Select 'Class Two',5 

Reference sql:

--2005.t-sqlSelectT.BJ,S.XH,S.NAME,S.CJ from @tjT CrossApply (SELECT TOP(T.num) withTies--Plus with ties, 4 people will be selected in one class (2 people tied to third place)XH,NAME,CJ from @student    whereT.bj=bj--the add where function is similar to inner join, and does not resemble a cross join    Order  byCjdesc) sOrder  by  Case  whenT.bj='Class One'  Then 1 Else 2 End ASC, S.CJdesc, S.xhASC    ---Sort 

Do you really play with SQL? Top and apply

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.