T-SQL JOIN不会带回有效结果,但单独查询会带来有效结果

mon*_*llc 0 sql t-sql database sql-server

我有一个查询适用于除一个订单之外的每个订单.这是现在不能正常工作的部分:

DECLARE @ordernum INT
SELECT @ordernum = 101257

SELECT  o.CustomerID , ups.*
            From dbo.orders o with (NOLOCK)
      left join (
           Select top 1 UPSAccountInfo.UPSAccount as UPSAccount1
      ,UPSAccountInfo.CID as UPSCID
      ,UPSAccountInfo.Address as  UPSAddress1
      ,UPSAccountInfo.DesiredService  UPSDesiredService1
      ,UPSAccountInfo.Address2 as UPSAddress2
      ,UPSAccountInfo.Suit as UPSSuite
      ,UPSAccountInfo.city as UPSCity
      ,UPSAccountInfo.Country as UPSCountry
      ,UPSAccountInfo.SP as UPSState
      ,UPSAccountInfo.Zip as UPSZip
  FROM UPSAccountInfo
  with (NOLOCK)
   order by date desc
      ) ups on ups.upscid = o.customerid
 WHERE o.OrderNumber = @ordernum
Run Code Online (Sandbox Code Playgroud)

这是一个更大的查询的一部分,我只是拿出了什么不起作用.通过不工作,我的意思是它返回customerid,但没有UPSAccountInfo.事实上,它正在带回一项纪录.

但是,这很好用:

Select top 1 UPSAccountInfo.UPSAccount as UPSAccount1
      ,UPSAccountInfo.CID as UPSCID
      ,UPSAccountInfo.Address as  UPSAddress1
      ,UPSAccountInfo.DesiredService  UPSDesiredService1
      ,UPSAccountInfo.Address2 as UPSAddress2
      ,UPSAccountInfo.Suit as UPSSuite
      ,UPSAccountInfo.city as UPSCity
      ,UPSAccountInfo.Country as UPSCountry
      ,UPSAccountInfo.SP as UPSState
      ,UPSAccountInfo.Zip as UPSZip
  FROM UPSAccountInfo
  WHERE CID = 58939
   order by date desc
Run Code Online (Sandbox Code Playgroud)

两个查询都有一个58939的customerid,所以发生了什么?

任何帮助表示赞赏.这已经好几个月了,但现在,对于这一个订单,它没有.这让我疯了.

哦,随意转储这个代码你想要的一切.我没有写它,我继承了它.

谢谢!

JNK*_*JNK 5

TOP 1在子查询中进行选择,但它没有相关性(因为它不能在a中JOIN).

因此,您的最新(TOP 1 ORDER BY DATE DESC=最新)记录没有相同的客户ID.

作为旁注,您的查询不等同.您的第二个查询包含一个WHERE子句,该子句将结果集限制为单个客户,这在顶部查询中不存在.