下面还有一个小例子,根据小例子可以将cross apply /outer apply 分别换成inner join /left join,结果是一样的,但是cross apply之后一般是带函数.
inner join之后一般是带表.
create
table
#T(姓名
varchar
(10))
insert
into
#T
values
(
'张三'
)
insert
into
#T
values
(
'李四'
)
insert
into
#T
values
(
NULL
)
create
table
#T2(姓名
varchar
(10) , 课程
varchar
(10) , 分数
int
)
insert
into
#T2
values
(
'张三'
,
'语文'
, 74)
insert
into
#T2
values
(
'张三'
,
'数学'
, 83)
insert
into
#T2
values
(
'张三'
,
'物理'
, 93)
insert
into
#T2
values
(
NULL
,
'数学'
, 50)
--drop table #t,#T2
go
select
*
from
#T a
cross
apply
(
select
课程,分数
from
#t2
where
姓名=a.姓名) b
/*
select
a.*,b.课程,b.分数from
#T a
inner
join#t2
b
where
a.姓名=b.姓名
*/
/*
姓名 课程 分数
---------- ---------- -----------
张三 语文 74
张三 数学 83
张三 物理 93
(3 行受影响)
*/
select
*
from
#T a
outer
apply
(
select
课程,分数
from
#t2
where
姓名=a.姓名) b
/*
select
a.*,b.课程,b.分数from
#T a
left join
#t2
b
where
a.姓名=b.姓名
*/
/*
姓名 课程 分数
---------- ---------- -----------
张三 语文 74
张三 数学 83
张三 物理 93
李四
NULL
NULL
NULL
NULL
NULL
(5 行受影响)
正好在查询cross apply与outer apply 区别的时候,同事看到了,然后就给了我下面的例子,解开了我之前的面试之谜。。。
(当时我用row_number,墨迹半天还觉得不对。。今天终于解决了)
选出每个source
的前100条数据!!
select * from b
cross apply
(select top 100 * from aqua_rpt.crd.crd_report_sft_derv_data a where b.source = a.source) a
当然也可以用下面的语句,但是由于 b表数据量很大,所以考虑到消耗内存太大,就采用 CTE.
select b.source,a.*
from aqua_rpt.crd.crd_report_sft_derv_data
b
cross apply
(select top 100 * from aqua_rpt.crd.crd_report_sft_derv_data a where b.source = a.source) a