我有一个查询适用于除一个订单之外的每个订单。这是现在不能正常工作的部分:
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
这是一个更大的查询的一部分,我只是拿出了什么不起作用。通过不工作,我的意思是它返回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
两个查询都有一个58939的customerid,那么发生了什么?
感谢任何帮助。这已经好几个月了,但现在,对于这一个订单,它没有。这让我疯了。
哦,您可以随意转储此代码。我没有写它,我继承了它。
谢谢!
答案 0 :(得分:5)
您在子查询中选择TOP 1
,但它没有相关性(因为它不能在JOIN
中)。
因此,您最新的(TOP 1 ORDER BY DATE DESC
=最新)记录没有相同的客户ID。
作为旁注,您的查询不等同。您的第二个查询包含一个WHERE
子句,该子句将结果集限制为单个客户,这在顶级查询中不存在。
答案 1 :(得分:2)
如果您只使用常规连接而不是子查询连接,该怎么办?像这样:
SELECT TOP 1
o.CustomerID
,ups.UPSAccount as UPSAccount1
,ups.CID as UPSCID
,ups.Address as UPSAddress1
,ups.DesiredService UPSDesiredService1
,ups.Address2 as UPSAddress2
,ups.Suit as UPSSuite
,ups.city as UPSCity
,ups.Country as UPSCountry
,ups.SP as UPSState
,ups.Zip as UPSZip
FROM dbo.orders o
LEFT OUTER JOIN UPSAccountInfo ups
ON ups.cid = o.customerid
WHERE o.OrderNumber = @ordernum
ORDER BY ups.date DESC
如果dbo.orders
不需要多行,则应该有效。