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

本文探讨了SQL中使用聚合函数进行数据汇总的方法,并详细解释了如何利用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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值