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