连接两个查询

时间:2013-02-25 17:53:33

标签: sql sql-server

我需要将第一个查询的数据用于第二个查询以获得正确的结果,但我无法完成它。谁可以帮助我。

     SELECT  [Project Nr], Task, TaskDate
     FROM    (
     SELECT   MSP_EpmProject_UserView.[Project Nr]
        ,MAX(CASE   WHEN [Task Type tempress] = 'Packed' 
                    THEN [Taskdeadline] 
                END) AS Pack
        ,MAX(CASE   WHEN [Task Type tempress] = 'Leave Production' 
                    THEN [Taskdeadline]
                END) AS [Leave Production]
        ,MAX(CASE   WHEN [Task Type tempress] = 'Flight Date' 
                    THEN [Taskdeadline]
                END) AS [Flight Date]
     FROM    MSP_EpmProject_UserView 
        LEFT JOIN MSP_EpmTask_UserView 
            ON MSP_EpmProject_UserView.ProjectUID = MSP_EpmTask_UserView.ProjectUID 
        LEFT JOIN MSP_EpmAssignment_UserView 
            ON MSP_EpmTask_UserView.TaskUID = MSP_EpmAssignment_UserView.TaskUID 
        LEFT JOIN MSP_EpmResource_UserView 
            ON MSP_EpmAssignment_UserView.ResourceUID = MSP_EpmResource_UserView.ResourceUID 
     WHERE (MSP_EpmTask_UserView.TaskIsProjectSummary = 0) 
     GROUP BY MSP_EpmProject_UserView.[Project Nr]

     ) data

     UNPIVOT        (
      TaskDate
      for [Task] in ([Pack],[Leave Vaassen],[Flight Date])
     ) piv

此部分查询必须使用上述查询的数据:

   select 
      * 
   from 
      M AllData
   inner join (
     select 
         ROW_NUMBER() OVER (Order by TaskDate) as ProductionOrder, 
        [Project Nr] 
     from 
        M
     where
         task = 'Leave Production'
    )
    ProductionOrder
    on ProductionOrder.[Project Nr] = AllData.[Project Nr]
    Order by
    ProductionOrder

2 个答案:

答案 0 :(得分:1)

您遗漏了很多重要的细节,例如您正在使用的DBMS以及您希望如何使用第一个查询,但如果您使用的是SQL Server 2005+,我建议您查看Common Table Expressions

with myCTE as
(
   --Your first query
)

--You can now use myCTE in another query...
SELECT * FROM myCTE

答案 1 :(得分:1)

我认为你在谈论相关子查询。您可以在http://msdn.microsoft.com/en-us/library/ms187638(v=sql.105).aspx找到一些信息。整点是外部查询连接到内部查询的每次迭代。我希望我能理解你的问题吗?