Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* Sample data */
insert into emp (EMPID, NAME, JOB, SALARY)
values
(201, 'ANIRUDDHA', 'ANALYST', 2100),
(212, 'LAKSHAY', 'DATA ENGINEER', 2700),
(209, 'SIDDHARTH', 'DATA ENGINEER', 3000),
(232, 'ABHIRAJ', 'DATA SCIENTIST', 2500),
(205, 'RAM', 'ANALYST', 2500),
(222, 'PRANAV', 'MANAGER', 4500),
(202, 'SUNIL', 'MANAGER', 4800),
(233, 'ABHISHEK', 'DATA SCIENTIST', 2800),
(244, 'PURVA', 'ANALYST', 2500),
(217, 'SHAROON', 'DATA SCIENTIST', 3000),
(216, 'PULKIT', 'DATA SCIENTIST', 3500),
(200, 'KUNAL', 'MANAGER', 5000);
/*Print total salary*/
select *, sum(salary) from emp;
/*Print total salary per job category*/
select job, sum(salary) from emp group by job;
/*Print total salary wtih every row*/
select *,
sum(salary) OVER() as total_salary
from emp;
/*Print total salary per job category*/
select *,
sum(salary) OVER(PARTITION BY job) as total_job_salary
from emp;
/*Order rows within partitions*/
select *,
sum(salary) over(partition by job order by salary desc) as ordered_job_salary
from emp;
/*Number rows using row_number*/
select *, ROW_NUMBER() over() as "row_number" from emp;
/*Number rows within each partition*/
select *, ROW_NUMBER() over(partition by job order by salary) as "partition_row_number" from emp;
/*Rank rows within each partition using rank function*/
select *,
ROW_NUMBER() over(partition by job order by salary) as "row_number",
RANK() over(partition by job order by salary) as "rank_row"
from emp;
/*Rank rows within each partition using dense_rank function*/
select *,
ROW_NUMBER() over(partition by job order by salary) as "row_number",
RANK() over(partition by job order by salary) as "rank_row",
DENSE_RANK() over(partition by job order by salary) as "dense_rank_row"
from emp;
/*Print first value within each partition using nth_value function*/
select *,
NTH_VALUE(name, 1) over(partition by job order by salary asc RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as "FIRST"
from emp;
/*Print last value within each partition using nth_value function*/
select *,
NTH_VALUE(name, 1) over(partition by job order by salary DESC RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as "LAST"
from emp;
/*Print nth value within each partition using nth_value function*/
select *,
NTH_VALUE(name, 3) over(partition by job order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as "THIRD"
from emp;
/*Statistics using ntile function*/
select *,
NTILE(4) over(order by salary) as "quartile"
from emp;
/*Lead values*/
select *,
LEAD(salary, 1) Over(partition by job order by salary) as sal_next
from emp;
/*Lag values*/
select *,
LAG(salary, 1) Over(partition by job order by salary) as sal_previous,
salary - LAG(salary, 1) Over(partition by job order by salary) as sal_diff
from emp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment