SubQueries
--------------------
Single Row_SubQuery
--------------------
--1. Find who is getting highest salary in the employee table?
select max(sal) from emp;
select *from emp where sal=(select max(sal) from emp);
select max(salary) from employees;
select *from employees where salary=(select max(salary) from employees);
--2.Find second maximum salary emp?
select *from emp where sal=(
select max(sal) from emp where sal!=(select max(sal) from emp));
select *from emp where sal=(
select max(sal) from emp where sal<>(select max(sal) from emp));
--3.Find the employees who are getting salary more than the average salary?
select round(avg(salary)) from employees;
select * from employees where salary>(select round(avg(salary)) from employees);
--4.Find emp who is earning more than BLAKE?
select *from emp where sal>(select sal from emp where ename='BLAKE');
--5.Find emp who has maximum experience
select hiredate from emp;
select min(hiredate) from emp;
select *from emp where hiredate=(select min(hiredate) from emp);
--6.Find emp who has minimum experience
select hiredate from emp;
select max(hiredate) from emp;
select *from emp where hiredate=(select max(hiredate) from emp);
select count(*) from emp group by deptno;
select max(count(*)) from emp group by deptno;
select deptno,count(*)from emp group by deptno having count(*)=(select max(count(*)) from emp group by deptno);
select deptno,max(count(*))from emp group by deptno;--not a single-group group function
---------------------
--. Find out the highest salaried employees for each department?
Two ways:
Using Rank()
select deptno, sal,Rank() over(partition by deptno order by sal desc) Rank from emp;
select
a.deptno,
a.sal
from
(select deptno, sal,Rank() over(partition by deptno order by sal desc) Rank from emp) a
where
a.Rank=1
group by a.deptno,a.sal;
Using Sub-Query
select max(sal) from emp;
select deptno,max(sal) from emp group by deptno;
select max(sal) from emp;
select max(sal) from emp group by deptno;
select deptno,max(sal) from emp group by deptno;
select *from emp where (deptno,sal) IN (select deptno,max(sal) from emp group by deptno);--must follow the order of the columns
Comments
Post a Comment