我收到错误(无法绑定多部分标识符“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
答案 0 :(得分: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