Q8. Company-wide salary statistics
Show the total number of employees, total salary, average salary (2 decimals), highest salary and lowest salary.
SELECT COUNT(*) AS total_employees,
SUM(salary) AS total_salary,
ROUND(AVG(salary), 2) AS avg_salary,
MAX(salary) AS max_salary,
MIN(salary) AS min_salary
FROM employees;
-- total_employees | total_salary | avg_salary | max_salary | min_salary
-- 20 | 1665000 | 83250.00 | 150000 | 48000Q9. Employees per department
Show the number of employees in each dept_id, largest first. Employees without a department must appear as their own group.
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
GROUP BY dept_id
ORDER BY emp_count DESC;
-- dept_id | emp_count
-- 1 | 7
-- 2 | 5
-- 4 | 4
-- 3 | 3
-- NULL | 1Q10. Departments with average salary above 80000
Show department ids whose average salary is more than 80000, with the average.
SELECT dept_id, ROUND(AVG(salary), 2) AS avg_salary
FROM employees
GROUP BY dept_id
HAVING AVG(salary) > 80000
ORDER BY avg_salary DESC;
-- dept_id | avg_salary
-- 1 | 101428.57
-- 4 | 84250.00Q11. Orders per status
Count orders for each status, highest count first.
SELECT status, COUNT(*) AS order_count
FROM orders
GROUP BY status
ORDER BY order_count DESC;
-- status | order_count
-- Delivered | 20
-- Shipped | 2
-- Cancelled | 2
-- Pending | 1Q12. Cities with at least 2 customers
Show cities that have 2 or more customers, with the customer count. Sort by count descending, then city.
SELECT city, COUNT(*) AS customer_count
FROM customers
GROUP BY city
HAVING COUNT(*) >= 2
ORDER BY customer_count DESC, city;
-- city | customer_count
-- Delhi | 4
-- Mumbai | 3
-- Bangalore | 2
-- Pune | 2Q13. COUNT(*) vs COUNT(column) vs COUNT(DISTINCT)
In one query, show the total customers, how many have an email, and how many distinct cities they live in.
SELECT COUNT(*) AS total_customers,
COUNT(email) AS with_email,
COUNT(DISTINCT city) AS distinct_cities
FROM customers;
-- total_customers | with_email | distinct_cities
-- 12 | 11 | 5Q14. Orders per month
Show the number of orders placed in each month of 2024.
SELECT EXTRACT(MONTH FROM order_date) AS order_month,
COUNT(*) AS order_count
FROM orders
GROUP BY EXTRACT(MONTH FROM order_date)
ORDER BY order_month;
-- order_month | order_count
-- 1 | 3
-- 2 | 4
-- 3 | 5
-- 4 | 4
-- 5 | 4
-- 6 | 5