20 SQL Queries Solutions
20 SQL Queries Solutions
-- 4. Sort the above query to show the earliest orders at the top.
-- Also display the customer who purchased these orders.
select so.order_id, so.order_date, p.name as product, c.name as customer
from sales_order so
join products p on p.id=so.prod_id
join customers c on c.id = so.customer_id
where lower(so.status) = 'completed'
order by so.order_date;
-- 6. For orders purchasing more than 1 item, how many are still
-- not completed?
select count(status) as not_completed_orders
from sales_order so
where quantity > 1
and lower(status) <> 'completed';
-- 9. Display the total sales and average sales done for each day.
select order_date, sum(quantity*price) as total_sales
, avg(quantity*p.price) as avg_sales
from sales_order so
join products p on p.id = so.prod_id
group by order_date
order by order_date;
-- 10. Display the customer name, employee name and total sale amount
-- of all orders which are either on hold or pending.
select c.name as customer, e.name as employee
, sum(quantity*p.price) as total_sales
from sales_order so
join employees e on e.id = so.emp_id
join customers c on c.id = so.customer_id
join products p on p.id = so.prod_id
where status in ('On Hold', 'Pending')
group by c.name, e.name;
-- 12. Fetch the orders which cost more than 2000 but did not include
-- the macbook pro. Print the total sale amount as well.
select (so.quantity * p.price) as total_sale, so.*
from sales_order so
join products p on p.id = so.prod_id
where prod_id not in (select id from products
where name = 'Macbook
Pro')
and (so.quantity * p.price) > 2000;
-- 13. Identify the customers who have not purchased any product yet.
select * from customers
where id not in (select distinct customer_id
from sales_order);
select c.*
from customers c
left join sales_order so on so.customer_id = c.id
where so.order_id is null;
select c.*
from sales_order so
right join customers c on so.customer_id = c.id
where so.order_id is null;
-- 16. Re-write the above query so as to display the total sales made
-- by each employee corresponding to each customer. If an employee
-- has not served a customer yet then display "-" under the customer.
select e.name as employee, coalesce(c.name, '-') as customer
, coalesce(sum(p.price * so.quantity),0) as total_sale
from sales_order so
join products p on p.id = so.prod_id
join customers c on c.id = so.customer_id
right join employees e on e.id = so.emp_id
and lower(so.status) = 'completed'
group by e.name, c.name
order by total_sale desc;
-- 19. Identify the customers who have purchased more than 5 products
select c.name as customer, sum(quantity) as total_products_purchased
from sales_order so
join customers c on c.id = so.customer_id
group by c.name
having sum(quantity) > 5;
from sales_order so