Let us have two tables
create table A (
fkb int,
groupby int
);
create table B (
id int,
search int
);
insert into A values (1, 1);
insert into B values (1, 1);
insert into B values (2, 1);
then the following query
select B.id, t.max_groupby - B.search diff
from B
cross apply (
select max(A.groupby) max_groupby
from A
where A.fkb = B.id
) t
return the expected result as follows
id diff
---------
1 0
2 NULL
However, when I add the group by A.fkb
into the cross apply, the B
row where the corresponding A.fkb
does not exist, disappear.
select B.id, t.max_groupby - B.search diff
from B
cross apply (
select max(A.groupby) max_groupby
from A
where A.fkb = B.id
group by A.fkb
) t
I was testing on SQL Server as well as on PostgreSQL (with cross join lateral
instead of cross apply
). Why the group by
makes the row disappear? It seems that the cross apply
behaves as an outer join in the first case and as an inner join in the latter case. However, it is not clear to me why.