You are on page 1of 32

Question 1.

1:
Table Name: orderdetails
Approach:
Columns to be displayed:
orderNumber
individualOrderAmount
totalOrderAmount

Select column names


Keywords: for similar order numbers, hence we use over (partition by
orderNumber)
For each order number: (quantity * price)
For total order amount : sum(quantity * price)
For orderNumber: to be arranged in increasing order i.e. use Order by
For individual order amounts: arrange in decreasing order
Solution 1:
select orderNumber, (quantityOrdered * priceEach) as
individualOrderAmount,
sum(quantityOrdered * priceEach) over (partition by
orderNumber) as totalOrderAmount
from orderdetails
order by orderNumber, individualOrderAmount desc;
The OVER clause

The OVER clause combined with PARTITION BY is used to break up data


into partitions
Syntax: function(…) OVER (PARTITION BY col1, col2,…)

For example:
COUNT(Gender) OVER (PARTITION BY GENDER) will partition the data
by GENDER i.e. there will be 2 partitions (Male and Female) and then
the COUNT() function is applied over each partition.
Any of the following functions can be used:
COUNT(), AVG(), SUM(), MIN(), MAX(), ROW_NUMBER(), RANK(),
DENSE_RANK() etc.
Difference between Group By and Partition By
• A Group By normally reduces the number of rows returned by rolling
them up and calculating averages or sums for each row.
• Group By clause can be used in a SELECT statement to collect data
across multiple records and group the results by one or more columns
• Partition By does not affect the number of rows returned, but it
changes how a window functions result is calculated.
• Using windowed aggregate functions instead of Group By, we can
retrieve both aggregated and non-aggregated values. The window
function is applied to each partition separately and computation
restarts for each partition.
Example for Group By and Partition By
Solution 2:
With raw_data as(
Select orderNumber, sum(priceEach * quantityordered) as
totalOrderAmount from orderdetails
Group by ordernumber)
Select a.orderNumber, (a.priceEach * a.quantityordered) as
individualOrderAmount, r.totalOrderAmount
From orderdetails a join raw_data r using(orderNumber)
Order by orderNumber, individualOrderAmount desc;
Common Table Expression (CTE)
• CTE is a temporary result set that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement, that
immediately follows the CTE.
• We can define one or more CTE’s
Syntax:
WITH cte_name(Column1, Column2,..)
As (CTE_query)

SQL query using CTE:


With EmployeeCount(DepartmentId, TotalEmployees)
as
(
Select DepartmentId, COUNT(*) as TotalEmployees
from tblEmployee
group by DepartmentId
)
Select DeptName, TotalEmployees
from tblDepartment
join EmployeeCount
on tblDepartment.DeptId = EmployeeCount.DepartmentId
order by TotalEmployees
Question 1.2
Solution
select *, avg(Runs) over (order by Year rows 4 preceding) as `Moving
Average’
from kohli_batting;
Rows Preceding
Rows Preceding specifies the aggregate functions in the current
partition in the OVER clause to consider the current row and a specific
number of rows before the current row.
Question 1.3
Solution:
Select *,
(case
when salary <= 2.5 then ‘A’
when salary > 2.5 and salary <= 5 then ‘B’
when salary > 5 and salary <= 10 then ‘C’
else ‘D’ end) as ‘Tax Slab’
from salaries;
Definition and Usage of Case statements
• The CASE statement goes through conditions and return a value when the
first condition is met (like an IF-THEN-ELSE statement). So, once a
condition is true, it will stop reading and return the result.
• If no conditions are true, it will return the value in the ELSE clause.
• If there is no ELSE part and no conditions are true, it returns NULL.
Syntax:
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;
Question 2.1:
Solution:
select *,
round(
case
when salary <= 2.5 then 0
when salary > 2.5 and salary <= 5 then ((salary – 2.5) * 0.05 * 100000)
when salary > 5 and salary < = 10 then (12500 + ((salary – 5) * 0.2 *
100000))
else (112500 + ((salary- 10)* 0.3 *100000))
end) as Taxamount
from salaries;
Question 2.2:
Solution:

Select country, count(*) as No_of_Sellers


from sellers group by country
Order by No_of_Sellers desc, country asc;
Question 2.3:
Solution
select * from sellers
where dayname(Joining_date) = ‘Monday’;

OR
select * from sellers
where weekday(Joining_date) = 0;
OR
select * from sellers
where dayofweek(Joining_date) = 2;
Few Day functions in MySQL:

• To extract the day, it can be achieved in the following several ways:


SELECT DAY("2017-06-15");
SELECT DAYOFMONTH("2017-06-15");
SELECT DAYOFWEEK("2017-06-15");
SELECT DAYOFYEAR("2017-06-15");
SELECT WEEKDAY("2017-06-15");
SELECT DAYNAME("2017-06-15");
Question 3.1:
Solution:
Derived table format:
Select r.emp_id, r.salary from
(select *, row_number() over() as SrNo from employee) r
Where SrNo % 2 != 0;

CTE format:
With row_table as
(select *, row_number() over() as SrNo from employee)
Select emp_id,salary from row_table
Where SrNo % 2 != 0;
DERIVED TABLE:
• Virtual table returned from a select statement
• Similar to a temporary table
• Using a Derived Table in SELECT statement is much simpler than a
temporary table because it does not require steps of creating a
temporary table
• The term Derived table and sub query is often used inter changeably
• When a stand-alone subquery is used in the FROM clause of a select
statement, it is called a Derived Table.
ROW_NUMBERS:
• Returns the sequential number of a row starting at 1
• ORDER BY clause is required
• PARTITION BY clause is optional
• When the data is partitioned, row number is reset to 1 when the partition
changes
Syntax: ROW_NUMBER() OVER (ORDER BY Col1, Col2)
Example:
Select Name, Gender, Salary
ROW_NUMBER() OVER (PARTITION BY GENDER ORDER BY Gender) as
RowNumber
from employees
Question 3.2:
Solution:
With sort_sal as
(select *, row_number() over(order by salary desc) as row_n
From employee)
Select emp_id, salary from sort_sal
Where row_n <= (select count(*) from employee) * 0.25;
OR
With sort_sal as
(select *, row_number() over(order by salary desc) as row_n
From employee)
Select emp_id, salary from sort_sal
Where row_n <= (select count(*) from employee) / 4;
Solution:
With sort_sal as
(select *, row_number() over(order by salary desc) as row_n
From employee)
Select emp_id, salary from sort_sal
Where row_n <= (select count(*)* 0.25 from employee) ;
OR
With sort_sal as
(select *, row_number() over(order by salary desc) as row_n
From employee)
Select emp_id, salary from sort_sal
Where row_n <= (select count(*)/4 from employee);
Question 3.3

Solution:
select *, rank() over(order by salary desc) as `rank’
from employee;
RANK and DENSE_RANK
• Returns a rank starting at 1 based on the ordering of rows imposed by
the ORDER BY clause
• ORDER BY clause is required
• PARTITION BY clause is optional
• When the data is partitioned, rank is reset to 1 when the partition
changes
Difference between RANK and DENSE_RANK functions
RANK function skips ranking(s) if there is a tie where as DENSE_RANK
will not
RANK() returns 1,1,3,4,5
DENSE_RANK() returns 1,1,2,3,4
Difference between RANK, DENSE_RANK & ROW_NUMBER

• ROW_NUMBER: Returns an increasing unique number for each row


starting at 1, even if there are duplicates
• RANK: Returns an increasing unique number for each row starting at 1.
When there are duplicates, same rank is assigned to all the duplicate
rows, but the next row after the duplicate rows will have the rank it
would have been assigned if there had been no duplicates. So RANK
function skips rankings if there are duplicates.
• DENSE_RANK:Returns an increasing unique number for each row
starting at 1. When there are duplicates, same rank is assigned to all the
duplicate rows but the DENSE_RANK function will not skip any ranks.
This means the next row after the duplicate rows will have the next
rank in the sequence.
REPRESENTATION USING QUERY AND TABLE:
SELECT Name, Salary, Gender,
ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNumber,
RANK() OVER (ORDER BY Salary DESC) AS [Rank],
DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank,
from employees;

You might also like