SQL2005連接函數Cross Apply與聚合函數誤用

/*
@T1:
ID          Name
----------- ---------------------
1           a
2           b
3           c

@T2:
ID          T1_ID       Num
----------- ----------- -----------
1           1           10
2           1           20
3           1           30
4           2           10

需要顯示結果:
Name                                               Num--合計
-------------------------------------------------- -----------
a                                                  60
b                                                  10

*/


declare @T1 Table(ID int primary key,Name nvarchar(50))
insert @T1 select 1,'a'
union all  select 2,'b'
union all  select 3,'c'

declare @T2 Table(ID int identity,T1_ID int,Num int)
insert @T2 select 1,10
union all  select 1,20
union all  select 1,30
union all  select 2,10

--要的結果:
select t1.Name,sum(T2.Num) as Num from @T1 t1 inner join @T2 t2 on t1.ID=t2.T1_id group by t1.Name

--用Cross apply替換時

select
    t1.Name,t2.Num
from @T1 t1
cross apply
    (select sum(Num) as Num from @T2 where T1.ID=T1_ID)t2

/*
Name                                               Num
-------------------------------------------------- -----------
a                                                  60
b                                                  10
c                                                  NULL --多了一個null值
*/

--處理加上:
select
    t1.Name,t2.Num
from @T1 t1
cross apply
    (select sum(Num) as Num from @T2 where T1.ID=T1_ID)t2
where t2.Num is not null


/*
需要顯示結果:
Name                                               MaxNum
-------------------------------------------------- -----------
a                                                  30
b                                                  10
*/

select t1.Name,Max(T2.Num) as MaxNum from @T1 t1 inner join @T2 t2 on t1.ID=t2.T1_id group by t1.Name


--用Cross apply替換時
select
    t1.Name,t2.MaxNum
from @T1 t1
cross apply
    (select max(Num) as MaxNum from @T2 where T1.ID=T1_ID)t2
/*
Name                                               MaxNum
-------------------------------------------------- -----------
a                                                  30
b                                                  10
c                                                  NULL --多了null
*/

--處理用Top 1

select
    t1.Name,t2.MaxNum
from @T1 t1
cross apply
    (select top 1 Num as MaxNum from @T2 where T1.ID=T1_ID order by Num desc)t2

原文地址:https://www.cnblogs.com/Roy_88/p/5463090.html