有用的SQL高级函数与查询

一.序号函数

# rank函数函数

根据排序子句给出递增的序号,但是存在并列并且跳空

顺序递增
select id, name, rank() over(order by cid) as rank from student;
 
跳过相同递增
select s.id, s.name, cid, c.name, rank() over(order by c.name) as rank 
from student s, classes c where cid = c.id;

 

# dense_rank函数

根据排序子句给出递增的序号,但是存在并列不跳空

不跳过,直接递增
select s.id, s.name, cid, c.name, dense_rank() over(order by c.name) as dense 
from student s, classes c where cid = c.id;

 

二.分组排序函数

# partition by分组子句

可以完成对分组的数据进行增加排序,partition by可以与以上三个函数联合使用。

利用partition by按照班级名称分组,学生id排序
select s.id, s.name, cid, c.name, row_number() over(partition by c.name order by s.id) as rank 
from student s, classes c where cid = c.id;
 
select s.id, s.name, cid, c.name, rank() over(partition by c.name order by s.id) as rank 
from student s, classes c where cid = c.id;
 
select s.id, s.name, cid, c.name, dense_rank() over(partition by c.name order by s.id) as rank 
from student s, classes c where cid = c.id;

 

三.联合查询

Ø 集合运算

操作两组查询结果,进行交集、并集、减集运算

1、 union和union all进行并集运算

--union 并集、不重复
select id, name from student where name like 'ja%'
union
select id, name from student where id = 4;
 
--并集、重复
select * from student where name like 'ja%'
union all
select * from student;

 

2、 intersect进行交集运算

--交集(相同部分)
select * from student where name like 'ja%'
intersect
select * from student;

 

3、 except进行减集运算

--减集(除相同部分)
select * from student where name like 'ja%'
except
select * from student where name like 'jas%';

四. 公式表表达式 相当于临时表

查询表的时候,有时候中间表需要重复使用,这些子查询被重复查询调用,不但效率低,而且可读性低,不利于理解。那么公式表表达式可以解决这个问题。

我们可以将公式表表达式(CET)视为临时结果集,在select、insert、update、delete或是create view语句的执行范围内进行定义。

--表达式
with statNum(id, num) as 
(
    select cid, count(*) 
    from student 
    where id > 0
    group by cid
)
select id, num from statNum order by id;
 
with statNum(id, num) as 
(
    select cid, count(*) 
    from student 
    where id > 0
    group by cid
)
select max(id), avg(num) from statNum;

 

五.使用自连接把表中所有重复的字段都查出来

select distinct s.* from student s, student s1 where s.id <> s1.id and s.sex = s1.sex;

具体例子:

create table a(id int,age int)

insert a select 1,20
union all select 2,20
union all select 3,21
union all select 4,22
union all select 5,23
union all select 6,23

select distinct s.* from a s, a s1 where s.id <> s1.id and s.age = s1.age;

 

六.自定义函数:返回table对象

create function fun_find_stuRecord(@id int)
    returns table
as
    return (select * from student where id = @id);
go
 
select * from dbo.fun_find_stuRecord(2);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值