简体   繁体   中英

Search using CROSS APPLY SQL Statement

I have the following SQL statement which returns results from a database in the format I need. However, I would like to use this query but add a search for where JobProducts.Serial = x

How can I add such a search?

SELECT  
J.CustomerID,  J.JobID, J.Status, J.Deleted, J.JobNo, Customers.CompanyName AS [Company], 
J.DateCreated AS [Date Created], derivedtbl_1.DueDate AS [Due Date] 

FROM 
Jobs  J LEFT OUTER JOIN Customers ON J.CustomerID = Customers.CustomerID CROSS APPLY 
(
SELECT   TOP (1) DueDate, JobProductID, JobID, ProductID, DepartmentID 
FROM      JobProducts AS JobProducts_1 
WHERE(JobProducts_1.JobID = J.JobID And Deleted = 0) 
ORDER BY DueDate
) AS derivedtbl_1 
//I know the line below wont work, but how could I achieve this?
WHERE JobProducts.Serial='123456'

The query uses the following tables Jobs, JobProducts, and Customers, where 1 Job can have many JobProducts, and 1 Customer can have many Jobs

I think you can just move it into the cross apply statement:

SELECT J.CustomerID,  J.JobID, J.Status, J.Deleted, J.JobNo, Customers.CompanyName AS [Company], 
       J.DateCreated AS [Date Created], derivedtbl_1.DueDate AS [Due Date] 
FROM Jobs J LEFT OUTER JOIN
     Customers
     ON J.CustomerID = Customers.CustomerID CROSS APPLY 
     (SELECT TOP (1) DueDate, JobProductID, JobID, ProductID, DepartmentID 
      FROM  JobProducts AS JobProducts_1 
      WHERE JobProducts_1.JobID = J.JobID And
            Deleted = 0 and
            JobProducts.Serial='123456'
      ORDER BY DueDate
     ) AS derivedtbl_1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM