从CTE中仅选择连接表中的列

时间:2015-03-13 19:39:24

标签: sql-server join common-table-expression

以下是我的CTE:

;WITH CTE AS
(SELECT O.*, E.Num, E.Amount 
FROM OData O
INNER JOIN Equip E
ON O.Name = E.Name)  
SELECT * FROM CTE -- gives results I want to join to 

以下是我想要SELECT的查询(并且仅对我的查询结果使用此SELECT语句:

SELECT 
    MU.Type
    ,MU.Num
    ,MU.MTBUR
    ,MF.MTBF
    ,MU.Hours 
    ,MF.Hours 
FROM 
    MUType_Stage MU
INNER JOIN 
    MFType_Stage MF
    ON
    MU.Type = MF.Type
    AND
    MU.Num = MF.Num

- 此处需要JOINCTE

INNER JOIN 
        Status_STAGE S
        ON
        MU.Nu = S.Part
    LEFT OUTER JOIN
        RCN N
        ON
        N.Name  = R.Part
    LEFT OUTER JOIN 
        Repair RR
        ON
        R.ACSS_Name = RR.Name

所以基本上我需要JOIN到我想要结果的CTE查询中的SELECT

OR ALTERNATIVELY 使用此select语句连接到CTE,但只使用第二个select语句中的选定列

1 个答案:

答案 0 :(得分:2)

试试这个语法

WITH CTE
     AS (SELECT O.*,
                E.Num,
                E.Amount
         FROM   OData O
                INNER JOIN Equip E
                        ON O.Name = E.Name)
SELECT MU.Type,
       MU.Num,
       MU.MTBUR,
       MF.MTBF,
       MU.Hours,
       MF.Hours
FROM   MUType_Stage MU
       INNER JOIN MFByACType_Stage MF
               ON MU.Type = MF.Type
                  AND MU.Num = MF.Num
       INNER JOIN CTE C --- JOIN HERE as like other tables
               ON C.Num = MF.Num
       INNER JOIN Status_STAGE S
               ON MU.Nu = S.Part
       LEFT OUTER JOIN RCN N
                    ON N.Name = R.Part
       LEFT OUTER JOIN Repair RR
                    ON R.ACSS_Name = RR.Name