sub select select jon" from tb1 t inner join(select t,b from tb2 where b = tb1.item2)t2 on t2.a = tb1.b"

时间:2016-05-25 16:27:52

标签: sql sql-server subquery inner-join where

美好的一天 我有以下查询

SELECT 
    G.guid, G.guLastName1, G.guFirstName1, G.guShowD,
    G.guPRInvit1 as guPR1, GP1.peN as guPR1N, pl.pppo  as POST,
    pl.pppe, pl.pppo
FROM Guests G 
left join Personnel GP1 on GP1.peID = G.guPRInvit1
LEFT JOIN (SELECT TOP 1 a.pppo, a.ppDT, a.pppe FROM PostsLog a where a.pppe = GP1.peID ) as pl
ON (pl.pppe = GP1.peID) --and DATEDIFF(DAY,pl.ppDT,G.guShowD)>=0)
WHERE 
G.guShowD between @datefrom and @DateTo and G.gusr = @SalesRoom

表PostsLog是表人员的位置日志然后我需要人员在日期范围内的位置

但在运行时我收到以下错误

The multi-part identifier "GP1.peID " could not be bound.
有人可以告诉我,我做错了。我不是很擅长SQL服务器,也找不到我的错误

2 个答案:

答案 0 :(得分:1)

这似乎是你真正的问题:

                                                              -------VV
LEFT JOIN (SELECT TOP 1 a.pppo, a.ppDT, a.pppe FROM PostsLog a where pl.pppe = GP1.peID ) as pl

pl别名用于子查询本身,因此可以在子查询中使用

我怀疑你的意思

                                                              -------V
LEFT JOIN (SELECT TOP 1 a.pppo, a.ppDT, a.pppe FROM PostsLog a where a.pppe = GP1.peID ) as pl

答案 1 :(得分:0)

删除子查询并将条件移至on子句:

select tb1.a, tb1.b, tb1.n, t2.a, t2.b 
from table1 tb1 inner join
     table2 t2
     on t2.b = tb1.n and t2.c = tb1.b
where 1 = 1 ;

您还有另一个错误,错过了tbl1.nt2.a之间的逗号,因为列别名中不允许(未转义)句点。此外,where条款是多余的;我猜你正在用代码构建查询。