簡體   English   中英

使用CROSS APPLY SQL語句進行搜索

[英]Search using CROSS APPLY SQL Statement

我有以下SQL語句,該語句以所需的格式從數據庫返回結果。 但是,我想使用此查詢,但要添加一個搜索,其中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和Customer,其中1個Job可以具有多個JobProducts,而1個Customer可以具有多個Jobs

我認為您可以將其移至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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM