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 

请有人帮助我:(

@蓝脚:

我想要这样的结果:

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 回答