0

このクエリを実行すると、エラーが発生します(マルチパート識別子 "f.FormID"をバインドできませんでした)。

select f.FormID, f.Title, fv.UserName
    from Forms f join (
        SELECT        FormID
            FROM            Reports
            WHERE        (ReportID = @ReportID)
        UNION 
        SELECT        FormRelations.ForigenFormID
        FROM            FormRelations INNER JOIN
                                    Forms ON FormRelations.ForigenFormID = Forms.FormID
        WHERE        (FormRelations.PrimaryFormID =
                            (SELECT        FormID
                            FROM            Reports
                            WHERE        (ReportID = @ReportID)))
        ) ids
        on f.FormID = ids.FormID

    LEFT OUTER JOIN (select top 1 UserName, FormID from FormValues where FormID = f.FormID and UserName = @UserName) fv
        ON f.FormID = fv.FormID 

誰か助けてください:(

@bluefeet:

私はそのような結果が欲しいです:

01304636-FABE-4A3E-9487-A14B012F9A61    item_1  1234567890
C0455E97-788A-4305-876A-A15000CFE928    item_2  1234567890
7719F37E-7021-4ABD-91ED-A15301830324    item_3  1234567890
4

1 に答える 1

1

そのようにサブクエリ内でエイリアスを使用する必要がある場合は、APPLY演算子の使用を検討することをお勧めします。

select f.FormID, f.Title, fv.UserName
from Forms f 
join 
(
    SELECT        FormID
    FROM            Reports
    WHERE        (ReportID = @ReportID)
    UNION 
    SELECT        FormRelations.ForigenFormID
    FROM            FormRelations 
    INNER JOIN Forms 
        ON FormRelations.ForigenFormID = Forms.FormID
    WHERE        (FormRelations.PrimaryFormID = (SELECT        FormID
                                                 FROM            Reports
                                                 WHERE        (ReportID = @ReportID)))
) ids
    on f.FormID = ids.FormID
CROSS APPLY
(
    select top 1 UserName, FormID 
    from FormValues 
    where FormID = f.FormID 
        and UserName = @UserName
) fv

または、次を使用できますrow_number()

select f.FormID, f.Title, fv.UserName
from Forms f 
join 
(
    SELECT        FormID
    FROM            Reports
    WHERE        (ReportID = @ReportID)
    UNION 
    SELECT        FormRelations.ForigenFormID
    FROM            FormRelations 
    INNER JOIN Forms 
        ON FormRelations.ForigenFormID = Forms.FormID
    WHERE        (FormRelations.PrimaryFormID = (SELECT        FormID
                                                 FROM            Reports
                                                 WHERE        (ReportID = @ReportID)))
) ids
    on f.FormID = ids.FormID
LEFT JOIN
(
    select UserName, FormID,
        ROW_NUMBER() over(PARTITION by FormID, UserName order by FormID) rn  
    from FormValues 
    where UserName = @UserName
) fv
    on f.FormID = fv.FormID
    and fv.rn = 1
于 2013-02-25T17:39:09.963 に答える