SQL 中连接表时出现问题
SELECT MID, FAD.FirstOpenedDate ,LCD.LastCloseDate
FROM mwMaster.dbo.Merchant M
JOIN (
SELECT MerchID, MIN(moddate) AS FirstOpenedDate
FROM mwMaster.dbo.MerchantStatusHistory
GROUP BY MerchID
) FAD ON FAD.MerchID = M.MerchID
LEFT JOIN (
SELECT MerchID, MAX(moddate) AS LastCloseDate
FROM mwMaster.dbo.MerchantStatusHistory
GROUP BY MerchID
) LCD ON LCD.MerchID = M.MerchID
JOIN (
SELECT merchid ,avg(Transactions) ,avg(Profit)
FROM mwMaster.dbo.ResidualSummary RS
WHERE RS.Date_Processed < LCD.LastCloseDate
GROUP BY Merchid
) R ON R.MerchID = M.MerchID
我在执行以下连接时遇到问题。我以前遇到过这个问题并使用了临时表,但想找出我做错了什么。基本上,不起作用的线路是倒数第三条线路。 “< LCD.LastClosDate”表示它无法绑定。是否可以使用我在上面的嵌套查询中创建的 LCD 值(在该查询中我以类似的方式使用了 M 表,但没有遇到任何问题)?我想因为 LCD 表是在这里动态创建的,所以它不能在嵌套查询中使用,但这只是我的猜测。
有什么想法吗?
顺便说一句,我还看到有人使用 CROSS 和 OVER。不熟悉它是如何工作的,但可能适用于这里?
SELECT MID, FAD.FirstOpenedDate ,LCD.LastCloseDate
FROM mwMaster.dbo.Merchant M
JOIN (
SELECT MerchID, MIN(moddate) AS FirstOpenedDate
FROM mwMaster.dbo.MerchantStatusHistory
GROUP BY MerchID
) FAD ON FAD.MerchID = M.MerchID
LEFT JOIN (
SELECT MerchID, MAX(moddate) AS LastCloseDate
FROM mwMaster.dbo.MerchantStatusHistory
GROUP BY MerchID
) LCD ON LCD.MerchID = M.MerchID
JOIN (
SELECT merchid ,avg(Transactions) ,avg(Profit)
FROM mwMaster.dbo.ResidualSummary RS
WHERE RS.Date_Processed < LCD.LastCloseDate
GROUP BY Merchid
) R ON R.MerchID = M.MerchID
I am having trouble performing the following join. I have run into this problem before and used temp tables but would like to find out what I am doing wrong. Basically the line that is not working is the 3rd to last. The "< LCD.LastClostDate" says that it cannot be bound. Is it possible to use the value from LCD which I created in a nested query above (in that query I used the M table in a similar way but I didnt run into any issue)? I am thinking becasue the LCD table is dynamically created here it cannot be used in the nested query but this is just my guess.
Any ideas?
On a side note I have also seen people using a CROSS and OVER. Not to farmiliar with how this works but may be applicable here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为虽然还没有测试过,你可以在 SQL 2005+ 中将 JOIN 更改为 CROSS APPLY
但使用 CTE 可能更容易
I think though haven't tested you can just change your JOIN to a CROSS APPLY in SQL 2005+
But it might be easier to use CTEs
如果没有您的数据,我无法真正测试这一点,但这是您可以做到的一种方法:
I can't really test this without your data, but here's one way you could do it: