sql日记(相关子查询,动态交叉表篇)
2024-07-21 02:11:35
供稿:网友
本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
最近重新又翻看了一下关于sqlserver的书籍,主要查看了一下关于sql中的相关子查询和交叉表方面的知识。
相关子查询和普通子查询区别在于:相关子查询引用了外部查询的列。
这种引用外部查询的能力意味着相关子查询不能自己独立运行,其中对于外部查询引用会使会使其无法正常执行。因此相关子查询的执行顺序如下:
1.首先执行一遍外部查询
2.对于外部查询的每一行分别执行一遍子查询,而且每次执行子查询时候都会引用外部的当前行的值。
使用子查询的结果来确定外部查询的结果集。
举个例子;
select t1.type
from titles t1
group by t1.type
having max(t1.advance) >=all
(select 2 * avg(t2.advance)
from titles t2
where t1.type = t2.type)
这个结果返回最高预付款超过给定组中平均预付款两倍的书籍类型。
在举个例子:
要求返回每一个编号的最大值(列出id,name,score)
id name(编号) score(分数)
1 a 88
2 b 76
3 c 66
4 c 90
5 b 77
6 a 56
7 b 77
8 c 67
9 a 44
select * from t a where score=
(select max(score) from t b where a.name=b.name)
再给一个排位的sql语句
select (
select count(*)+1 as dd
from [test ] as a where a.[f2]<b.[f2] ) as ord,b.[f1], b.[f2]
from [test ] as b
order by b.[f2];
好了关于sql的相关子查询先讲到这里。
下面说一下交叉表的概念
说到交叉表先提一下递归的select变量
递归的select变量可以使用select语句和子查询将一个变量与其自身拼接起来。
举一个例子
select @[email protected] +d.column from table1 a
从而将基础表中垂直的列数据改为水平方向的数据。这样就可以替代游标。
下面就是动态交叉表和静态的交叉表的一个比较,动态的交叉表这样就代替了传统的游标。
交叉表
方法1
select f_number as '学员',
sum(case f_subject when 'a01' then f_num end) as 'a01',
sum(case f_subject when 'a02' then f_num end) as 'a02' ,
sum(case f_subject when 'a03' then f_num end) as 'a03' ,
sum(case f_subject when 'a04' then f_num end) as 'a04' ,
sum(case f_subject when 'a05' then f_num end) as 'a05' ,
sum(case f_subject when 'a06' then f_num end) as 'a06' ,
sum(case f_subject when 'a07' then f_num end) as 'a07' ,
sum(case f_subject when 'a08' then f_num end) as 'a08' ,
sum(case f_subject when 'a09' then f_num end) as 'a09'
from rowdata group by f_number order by f_number
方法2
declare @sql nvarchar(2000)
set @sql=''
select @[email protected]+ 'sum(case f_subject when '''+ a.f_subject +''' then f_num else 0 end) as '
+a.f_name+','
from (select distinct top 100 percent f_subject,f_name from rowdata b join subject_name c on b.f_subject=c.f_number order by f_subject ) a
set @sql='select f_number as '+'"学员",'[email protected] + 'count(f_number) as '+'"考试数目"'+
'from rowdata group by f_number order by f_number'
print @sql
exec sp_executesql @sql