2013-07-29 63 views
0

我有以下SQL語句,它以我需要的格式從數據庫返回結果。但是,我想使用此查詢,但添加了一個搜索JobProducts.Serial = x使用CROSS APPLY SQL進行搜索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) 
ORDER BY DueDate 
) AS derivedtbl_1 
//I know the line below wont work, but how could I achieve this? 
WHERE JobProducts.Serial='123456' 

該查詢使用下表作業,JobProducts,和客戶,其中1個人職位可以有很多JobProducts,和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; 
+0

這很好用!謝謝你的幫助 – user1711657