试图修改有问题的多联接查询

时间:2018-07-31 17:49:51

标签: sql sql-server join ssms

我有一个简化的查询,如下所示,它可以进行多个连接。我正在尝试添加一个要选择的字段,但是在不更改出现的记录数的情况下,我找不到找到连接该字段的好方法...

SELECT tblApp.AppID
,'Type' = tblRef.Label
,'Status' = tblRef2.Label
FROM (
(
    (
        tblApp LEFT JOIN tblAppExt ON tblApp.AppID = tblAppExt.AppID
        ) LEFT JOIN tblRef ON tblApp.AppTypeID = tblReferenceData.ID
    ) LEFT JOIN tblRef tblRef2 ON tblApp.AppStatusID = tblRef2.ID
)

原样-我得到149个结果,如果我尝试以任何方式加入它,我得到的记录数量将是10倍。我希望做的是能够选择另一个领域。我希望加入具有AppID的tblAppExt2,就像查询的FROM部分中的其他表一样,所以我的目标基本上是这样做:

    SELECT tblApp.AppID
    ,'Type' = tblRef.Label
    ,'Status' = tblRef2.Label
    ,'NewField' = tblAppExt2.NewField

2 个答案:

答案 0 :(得分:1)

首先要尝试的是DISTINCT:

SELECT DISTINCT
    tblApp.AppID 
    , [Type] = tblRef.Label
    , [Status] = tblRef2.Label
    , [NewField] = tblAppExt2.NewField
FROM tblApp
    LEFT JOIN tblAppExt 
        ON tblApp.AppID = tblAppExt.AppID
    LEFT JOIN tblRef 
        ON tblApp.AppTypeID = tblReferenceData.ID
    LEFT JOIN tblRef tblRef2 
        ON tblApp.AppStatusID = tblRef2.ID
    LEFT JOIN tblAppExt2.NewField 
        ON something = somethingElse ;

如果这不起作用,则表示[NewField]有多个不同的值,您需要告诉它如何选择正确的值。例如,要获取最新的[NewField],可以将CTE与ROW_NUMBER函数一起使用:

; WITH AllRecords
AS (
    SELECT DISTINCT
        tblApp.AppID 
        , [Type] = tblRef.Label
        , [Status] = tblRef2.Label
        , [NewField] = tblAppExt2.NewField
        , MyRank = ROW_NUMBER() OVER(PARTITION BY tblApp.ID ORDER BY tblAppExt2.DateEntered DESC)
    FROM tblApp
        LEFT JOIN tblAppExt 
            ON tblApp.AppID = tblAppExt.AppID
        LEFT JOIN tblRef 
            ON tblApp.AppTypeID = tblReferenceData.ID
        LEFT JOIN tblRef tblRef2 
            ON tblApp.AppStatusID = tblRef2.ID
        LEFT JOIN tblAppExt2.NewField 
            ON something = somethingElse
        )
SELECT *
FROM AllRecords
WHERE AllRecords.MyRank = 1 ;

答案 1 :(得分:1)

您可以使用| ColA | Locations | |-------------|----------------| | 1 | Texas | | 1 | Colorado | | 1 | Missouri | | 1 | Kansas | | 2 | Texas | | 2 | Colorado | | 2 | Missouri | | 2 | Kansas | 或相关的outer apply

subquery