如何将两个选择嵌套在一起

时间:2017-10-24 19:26:56

标签: sql sql-server tsql

我正在尝试编写一个存储过程,它将所有作业编号的最新PM日期提供给当前作业查询。当前的工作查询如下:

SELECT      
    [dbo].[ServiceTicket].[FormID]
    ,[dbo].[Job].[JobNumber]
    ,[dbo].[ServiceTicket].[EditTS] AS 'LastVisitDate'  
    ,[CustomerName]
    ,[ShiptoCity]
    ,[dbo].[JobType].[Description] AS 'JobTypeName'     
    ,[dbo].[EquipmentList].TagNumber
    ,[dbo].[Technician].[Name]
    ,[dbo].[JobStatus].[Description] AS 'JobStatus'
    ,[dbo].[Equipment].[EquipmentName]
    ,[dbo].[Equipment].[Amount]
    ,[dbo].[EquipmentList].[EquipmentMake]
FROM   
    [dbo].[Job]     
INNER JOIN 
    [dbo].[JobType] ON [dbo].[Job].JobTypeID = [dbo].[JobType].ID
INNER JOIN 
    [dbo].[ServiceTicket] ON [dbo].[Job].JobNumber = [dbo].[ServiceTicket].JobNumber
INNER JOIN 
    [dbo].[EquipmentList] ON [dbo].[ServiceTicket].FormID = [dbo].[EquipmentList].LastFormID
INNER JOIN 
    [dbo].[Technician] ON [dbo].[ServiceTicket].FormID = [dbo].[Technician].FormID
INNER JOIN 
    [dbo].[JobStatus] ON [dbo].[ServiceTicket].JobStatus = [dbo].[JobStatus].ID
INNER JOIN 
    [dbo].[Equipment] ON [dbo].[EquipmentList].LastFormID = [dbo].[Equipment].[FormID]
WHERE  
    [dbo].[Job].[JobNumber] NOT IN ('1')
    AND [dbo].[EquipmentList].[EquipmentStatusId] = 1 --Rented 
    AND [dbo].[Job].JobTypeID BETWEEN 1 AND 6
    AND [dbo].[ServiceTicket].JobStatus IN (1,2,3,5,6,8,9,10)
    AND [dbo].[ServiceTicket].JobNumber NOT IN (SELECT JobNumber 
                                                FROM [dbo].[ServiceTicket] 
                                                WHERE  [dbo].[ServiceTicket].JobStatus IN (4,7))
ORDER BY 
    [dbo].[Job].Jobnumber

下面的查询是我想要嵌入的,嵌套的?,上面的查询:

SELECT
    [dbo].[ServiceTicket].[JobNumber]
    ,Max(EditTS) As 'LastPMDate'
FROM 
    [dbo].[ServiceTicket]
WHERE 
    servicetickettype IN (11,12,13,14,15,16,17,7)
GROUP BY
    [dbo].[ServiceTicket].[JobNumber]

1 个答案:

答案 0 :(得分:0)

嵌套可能意味着很多事情,但我猜你想将LastPMDate添加到你的选择中。一种方法是在FROM子句中使用内联视图

...

 INNER JOIN [dbo].[ServiceTicket]
        ON [dbo].[Job].JobNumber = [dbo].[ServiceTicket].JobNumber

 INNER JOIN ( SELECT [dbo].[ServiceTicket].[JobNumber] ,Max(EditTS) As'LastPMDate'
           FROM [dbo].[ServiceTicket] 
           WHERE servicetickettype IN (11,12,13,14,15,16,17,7)
           Group By [dbo].[ServiceTicket].[JobNumber]) AS editTime
 ON  [dbo].[ServiceTicket].JobNumber = editTime. JobNumber 
...

然后您就可以将LastPMDate添加到SELECT

您还可以在ORACLE和DBMS中使用SQL Server中的公用表表达式或WITH子句。

您也可以将此Select添加到SELECT子句并将连接条件添加到嵌套SQL中的WHERE子句中,但我不建议