This article brings you relevant knowledge about SQL server. It mainly introduces the method of SQL Server using CROSS APPLY and OUTER APPLY to implement connection queries. The article introduces it in detail through sample code. , let’s take a look at it, I hope it will be helpful to everyone.
Recommended study: "SQL Tutorial"
CROSS APPLY and OUTER APPLY can do:
When one record in the left table is associated with multiple records in the right table, I need to control whether one or more records in the right table match the left table.
There are two tables: Student (student table) and Score (score table). The data are as follows:
ROSS APPLY means "cross-application". When querying, the left table is first queried, and then each record in the right table is matched with the current record in the left table. If the match is successful, the records of the left table and the right table will be merged into one record and output; if the match fails, the records of the left table and the right table will be discarded. (Similar to INNER JOIN)
Query the last two test scores of each student.
SELECT T1.StudentNo, T1.Name, T2.ExamScore, T2.ExamDate FROM Student AS T1 CROSS APPLY ( SELECT TOP 2 * FROM Score AS T WHERE T1.StudentNo = T.StudentNo ORDER BY T.ExamDate DESC ) AS T2
Result:
SELECT T1.StudentNo, T1.Name, T2.ExamScore, T2.ExamDate FROM Student AS T1 OUTER APPLY ( SELECT TOP 2 * FROM Score AS T WHERE T1.StudentNo = T.StudentNo ORDER BY T.ExamDate DESC ) AS T2
SELECT * FROM #T a CROSS APPLY [dbo].[F_TConversion](a.num)
SELECT b.* FROM ( select Subject='Chiness',num=1 union all select 'Math',2 union all select 'English',3) a cross apply (select top(a.num) * from Students where Subject=a.Subject ) b
SQL tutorial》
The above is the detailed content of SQL Server uses CROSS APPLY and OUTER APPLY to implement connection queries. For more information, please follow other related articles on the PHP Chinese website!