SQL 数据库高级查询

2022/5/25 2:20:30

本文主要是介绍SQL 数据库高级查询,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

一.聚合函数

1.sum()求和

select sum(age)from 库名

2,。count ()统计有多少条记录

select count(*)from 库名

3.avg() 求平均值

select avg(age)from 库名

4. max ()求最大值

select max(age)from 库名

5.min ()求最小值

select min (age) from 库名

二 .聚合函数和分数函数搭配运用

group by 

select 列名+聚合函数 from 库名group by 列名 having +聚合函数;

三. 联表查询

1.内部 inner join

2.左联表 left join

3.右联表 right join

4.全部联表查询 full join

 

 

 

 

 

 

 

 

--模糊查询

--5、查询所有梁姓家庭成员(like)

select * from tb_users where uname like '梁%'

--6、查询日常收支表中所有rmenu即备注含‘去’字的记录

select * from tb_inoutinfo where rmenu like '%去%'

--7、查询日常收支表中2月到3月之间的收支情况(between)

select * from tb_inoutinfo where month(rdate) between 2 and 3

--8、查询日常收支表中1000到5000之间金额的收支记录

select * from tb_inoutinfo where rmoney between 1000 and 5000

--9、查询日常收支表中工资和奖金记录,即xid为1,2的记录

select * from tb_inoutinfo where xid in(1,2)

--聚合函数

--10、求存款额,即对金额求和

select sum(rmoney) as 总收入from tb_inoutinfo where rmoney>0

--11、求总支出,即为金额为负数的求和

select sum(rmoney) as 总支出from tb_inoutinfo where rmoney<0

select * from (select sum(rmoney) as 总收入from tb_inoutinfo where rmoney>0 )a join (select sum(rmoney) as 总支出from tb_inoutinfo where rmoney<0)b on 1=1

--12、求梁山伯今年发了几次工资,即为uid为1且xid为1的记录记数

select * from tb_inoutinfo where uid=1 and xid=1

--13、最大收入额,即求最大值

select max(rmoney) from tb_inoutinfo

--分组

--14、求每个人的财务金额和,即根据uid分组后求rmoney的和

select uid,sum(rmoney) from tb_inoutinfo group by uid

--15、求每个人的支出金额,即条件为rmoney为负数,根据uid分组求rmoney的和

select uid,sum(rmoney) from tb_inoutinfo where rmoney<0 group by uid

--16、求每个人的收入金额,但只显示超过10000元,即条件为rmoney大于0, 根据uid分组求和,并有having筛选大于10000的

select uid as 成员编号,sum(rmoney) as 金额from tb_inoutinfo where rmoney>0 group by uid having sum(rmoney)>10000

--17、求入支出项目个数,即在项目表中按收支类型分组,再计数

select xid,sum(rmoney) from tb_inoutinfo group by xid

--联表查询

--18、在收支项目表和日常收支表中查询项目编号,项目名称,收支类型,收支金额

select rid,xname,xtype,rmoney from tb_inoutinfo a left join tb_inoutfield b on a.xid=b.xid

--19、在成员表和日常收支表中查询家庭角色,姓名,金额,操作日期

select a.uid,uname,upart,rmoney,rdate from tb_users a join tb_inoutinfo b on a.uid=b.uid

--20、在收支项目表和日期收支表,成员表中查询姓名,项目名称,收支金额

select uname,xname,xtype,rmoney,rdate from tb_users a join tb_inoutinfo b on a.uid=b.uid join tb_inoutfield c on b.xid=c.xid

 

 



这篇关于SQL 数据库高级查询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程