【问题标题】:Why CROSS APPLY and INNER JOIN returns different result为什么 CROSS APPLY 和 INNER JOIN 返回不同的结果
【发布时间】:2022-01-01 13:21:17
【问题描述】:

为什么使用交叉应用返回额外的行。它不应该类似于 INNER JOIN 吗? 我期望的结果是

QuoteID  controlNo  etc            MaxQuoteID   COntrolNo
10101     1111     something15     10101        1111

样本数据:

-- create first example table
drop table if exists #test1
create table #test1 (QuoteID int, controlNo int, etc varchar(100))
insert into #test1 values 
(1111, 1111,'something1'),
(10101, 1111,'something15'),
(2222, 2222,'something2'),
(3333, 3333,'something3'),
(3333, 30303,'something35'),
(4444, 4444,'something4')
select * from #test1

--create second example table
drop table if exists #test2
create table #test2 (QuoteID int, ControlNo int)
insert into #test2 values 
(1111,1111),
(10101,1111)
select * from #test2

-- resutl query 1. This one works as expected
select * 
from #test1 t
inner join (select max(QuoteID) as MaxQuoteID, COntrolNo from #test2 group by ControlNo) tt ON t.QuoteID = tt.MaxQuoteID

-- But why this one doesnt work?
select * 
from #test1 t
cross apply 
(
-- subquery returns a single quoteid 10101, which is what I need
select max(QuoteID) as QuoteID
from #test2 tt
where tt.QuoteID = t.QuoteID
group by ControlNo
) a

【问题讨论】:

  • 为什么他们不应该返回不同的结果?如果您希望我们对它们进行批评,您需要告诉我们为什么您有这些期望,并根据权威文档进行论证。 “我们读不懂你的心思。”否则,您只是要求对语言进行另一种演示,不知道您已经不理解什么。 “额外行”和“应该类似于”也不清楚。使用足够多的单词、句子和对部分示例的引用来清楚完整地表达你的意思。 How to AskHelp centerminimal reproducible example
  • 这是一个常见问题解答。请在考虑发布之前阅读手册和谷歌任何错误消息以及您的问题/问题/目标的许多清晰、简洁和准确的措辞,带有和不带有您的特定名称/字符串/数字、“site:stackoverflow.com”和标签;阅读许多答案。反映您的研究。

标签: sql-server tsql join cross-apply


【解决方案1】:

两个查询都不一样。

在查询 1 中,您需要 max(QuoteID)controlNo

在查询 2 中,您将获得每个 controlNomax(QuoteID)

如果您想使用CROSS APPLY 等效,应该是

select  * 
from    #test1 t
        cross apply 
        (
            select  max(tt.QuoteID) as QuoteID, tt.controlNo
            from    #test2 tt
            group by tt.controlNo
            having  max(QuoteID) = t.QuoteID
        ) a

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-16
    • 2019-02-18
    • 2023-03-16
    • 2014-11-15
    • 2010-11-11
    • 2016-04-10
    • 1970-01-01
    相关资源
    最近更新 更多