0

我想在底部概括我的查询,以便我获得所有项目和附加项目信息,其中我的子组具有一定的价值,但我无法让它工作,因为我无法获得 [ProjectFk]

SELECT 
      [HeadCount].[ID],
      [LinkProjectAreaFk],
      [Month1],
      [Month2],
      [Month3],
      [Month4],
      [Month5],
      [Month6],
      [Month7],
      [Month8],
      [Month9],
      [Month10],
      [Month11],
      [Month12],
      [HcYear],
      [ApproveDirFk],
      [ApproveDirDate],
      [FreezeFk],
      [freezeDate],
      [CDSID],[FreezeTypeFk],
      [ApproveDirTypeFk],
      [SourcesFk], 
      [Project].[Title], 
      [Project].[Title]
FROM 
     [HeadCount], 
      [Project] 
WHERE 
      [HeadCount].[LinkProjectAreaFk] 
   IN 
      (SELECT 
               [ID] 
       FROM 
               [LinkProject-Area]
       WHERE
       [SubgroupFk]=1)
  and
       [Project].[ID]=[LinkProject-Area].[ProjectFk]

以下查询有效,但仅适用于一个项目我怎样才能从我的子查询中获取 projectFk,因为当我查找它时,他们说这是不可能的,并且使用左外连接我根本无法让它工作

SELECT 
      [HeadCount].[ID],
      [LinkProjectAreaFk],
      [Month1],
      [Month2],
      [Month3],
      [Month4],
      [Month5],
      [Month6],
      [Month7],
      [Month8],
      [Month9],
      [Month10],
      [Month11],
      [Month12],
      [HcYear],
      [ApproveDirFk],
      [ApproveDirDate],
      [FreezeFk],
      [freezeDate],
      [CDSID],
      [FreezeTypeFk],
      [ApproveDirTypeFk],
      [SourcesFk], 
      [Project].[Title],
       [Project].[Title]
FROM 
      [HeadCount], 
       [Project] 
WHERE 
       [HeadCount].[LinkProjectAreaFk] IN 
      (SELECT 
            [ID] 
       FROM 
             [LinkProject-Area] 
       WHERE 
             [ProjectFk]=90 
       and 
             [SubgroupFk]=1)
        and 
             [Project].[ID]=90

希望你能帮助我或指出我正确的方向

亲切的问候


嗨,我一直在尝试你的方式,但它仍然没有按预期进行:我得到了无法绑定的多部分标识符“MyCTE.ProjectFK”。并且无法绑定多部分标识符“MyCTE.ID”。当我查找时出错与使用我的连接错误有关吗?

     ;WITH MyCTE (ID, ProjectFK) 
    AS 
    (     
    SELECT 
           ID, 
            ProjectFk     
    FROM 
           [LinkProject-Area]     
    WHERE 
           SubgroupFk = 1 
    ) 

    SELECT 
           * 
   FROM 
             [LinkProject-Area] 
   INNER JOIN 
          HeadCount ON [LinkProjectAreaFk] = MyCTE.ID 
    INNER JOIN
           Project ON Project.ID = MyCTE.ProjectFK
4

1 回答 1

0

我想你会想要像这样组织这个查询:

SELECT ...
FROM
(
    SELECT ID, ProjectFk
    FROM [LinkProject-Area]
    WHERE SubgroupFk = 1
) LinkProjectAreas
INNER JOIN HeadCount ON LinkProjectAreaFK = LinkProjectAreas.ID
INNER JOIN Project ON Project.ID = LinkProjectAreas.ProjectFK

您还可以使用公用表表达式 (CTE) 来组织它:

;WITH LinkProjectAreas (ID, ProjectFK) AS
(
    SELECT ID, ProjectFk
    FROM [LinkProject-Area]
    WHERE SubgroupFk = 1
)
SELECT ...
FROM LinkProjectAreas
INNER JOIN HeadCount ON LinkProjectAreaFK = LinkProjectAreas.ID
INNER JOIN Project ON Project.ID = LinkProjectAreas.ProjectFK
于 2012-07-10T23:00:23.050 回答