Question

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

Was it helpful?

Solution

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top