Problem Description
Refer the following two tables and answer the question
Table Name – Customer
Description- Records all the customer data
CustomerI FirstNam LastNam
d e e Email DoB Phone
1 Atul Mohan
[email protected] 1982-10-10 00:00:00 9886651288
2 Armaan Shaah
[email protected] 1983-12-12 00:00:00 9886651266
3 Jitu Bagwani
[email protected] 1989-01-01 00:00:00 8877665544
[email protected] 4 Sherine Mathew m 1987-02-02 00:00:00 8812345611
Table Name – Sales
Description – Records all the sales.
Cust_I Sale_Amoun
d Date t
1 2011-02-09 00:00:00 700
2 2010-09-09 00:00:00 600
1 2010-09-09 00:00:00 900
3 2010-09-09 00:00:00 200
Question 1 - You need to write a SQL to print the Customer First Name, Last Name and the total sales
happened for all the customers. If there is no sales record for a particular customer, it should print the
first name, last name of the customer and the total sales amount as 0. Below is the sample output.
SalesPerCustome
FirstName LastName r
Jitu Bagwani 200
Sherine Mathew 0
Atul Mohan 1600
Armaan Shaah 600
Solution 1
/**This is MySQL version. Alternatively, we can use NVL() for Oracle***/
SELECT Customer.FirstName, Customer.LastName
,IF(SUM(Sales.Sale_Amount) IS NULL, 0,SUM(Sales.Sale_Amount) ) AS SalesPerCustomer
FROM Customer LEFT JOIN Sales
ON Customer.CustomerID = Sales.Cust_Id
GROUP BY Customer.FirstName, Customer.LastName
ORDER BY Customer.LastName
Question 2 - You need to write a SQL to print the Customer First Name, Last Name and the total sales
happened for all the customers whose year of birth is 1983 or thereafter. If there is no sales record for a
particular customer, it should print the first name, last name of the customer and the total sales amount
as 0. Below is the sample output.
FirstNam LastNam SalesPerCustom
e e er
Jitu Bagwani 200
Sherine Mathew 0
Armaan Shaah 600
SELECT Customer.FirstName, Customer.LastName
,IF(SUM(Sales.Sale_Amount) IS NULL, 0,SUM(Sales.Sale_Amount) ) AS SalesPerCustomer
FROM Customer LEFT JOIN Sales
ON Customer.CustomerID = Sales.Cust_Id
WHERE YEAR(Customer.Dob)>'1982'
GROUP BY Customer.FirstName, Customer.LastName
ORDER BY Customer.LastName