为什么 CROSS APPLY 和 INNER JOIN returns 不同的结果
Why CROSS APPLY and INNER JOIN returns different result
为什么要交叉应用 return 额外的行。它的工作方式不应该类似于 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
两个查询不一样。
在查询 1 中,您希望 max(QuoteID)
按 controlNo
分组
在查询 2 中,每个 controlNo
得到 max(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
为什么要交叉应用 return 额外的行。它的工作方式不应该类似于 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
两个查询不一样。
在查询 1 中,您希望 max(QuoteID)
按 controlNo
在查询 2 中,每个 controlNo
max(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