sql之二
1.各個部門薪水和
select
deptno,sum(sal)
from emp
group by deptno;
2.各部門各崗位薪水和
select
deptno,job,sum(sal)
from emp
group by deptno,job;
3.各部門各崗位薪水和大於3000
select
deptno,job,sum(sal)
from emp
group by deptno,job
having sum(sal)>3000;
子表別名
select * from
(select
deptno,job,sum(sal) as sum_sal
from emp
group by deptno,job) as t
where t.sum_sal >3000;
4.組合
select
deptno,job,sum(sal)
from emp
where job=‘SALESMAN’
group by deptno,job
having sum(sal)>3000
order by sum(sal) desc
limit 1;
inner join:內連線
left join:左連線
right join:右連線
create table testa(aid int,aname varchar(100));
create table testb(bid int,bname varchar(100),age int);
insert into testa values(1,‘tianming’);
insert into testa values(2,‘si’);
insert into testa values(3,‘ben’);
insert into testa values(4,‘doudou’);
insert into testa values(5,‘yan’);
insert into testb values(1,‘tianming’,15);
insert into testb values(2,‘si’,16);
insert into testb values(3,‘ben’,17);
insert into testb values(4,‘doudou’,18);
insert into testb values(7,‘feng’,19);
insert into testb values(8,‘ruoze’,20);
insert into testb values(9,‘jepson’,21);
– left join:右表匹配左表,左表全,匹配不到null
select
a.aid,a.aname,
b.bid,b.bname
from testa as a
left join testb as b on a.aid=b.bid;
– right join:
select
a.aid,a.aname,
b.bid,b.bname
from testa as a
right join testb as b on a.aid=b.bid;
– inner join 只匹配相同的
select
a.aid,a.aname,
b.bid,b.bname
from testa as a
inner join testb as b on a.aid=b.bid;
– 根據id和name匹配
select
a.aid,a.aname,
b.bid,b.bname
from testa as a
left join testb as b on
a.aid=b.bid and a.aname=b.bname;
select
a.ename,a.deptno,b.dname,b.loc
from emp a
left join dept b on a.deptno=b.deptno;
– between and
– ifnull(a,0) 如果a是null,變為0,null值欄位相加還是null