0

我有以下 SQL 语句,它以我需要的格式从数据库返回结果。但是,我想使用此查询,但添加搜索 where JobProducts.Serial = x

如何添加这样的搜索?

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'

查询使用以下表 Jobs、JobProducts 和 Customers,其中 1 个 Job 可以有多个 JobProducts,1 个 Customer 可以有多个 Jobs

4

1 回答 1

0

我认为您可以将其移至cross apply声明中:

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;
于 2013-07-29T23:23:41.693 回答