Question: Creating Views
Explore how to create and manage SQL views that combine data from multiple tables, enabling efficient retrieval of sales reports with employee, category, and sales details.
We'll cover the following...
Question
We have a database for a company that manages information about its employees, the product categories they handle, the products within those categories, and the sales made. The Employees table stores unique identifiers (EID), employee names, and ages. The ProductCategories table contains unique identifiers (CategoryID) for each category and assigns one employee to manage each. The Products table contains identifiers (PID) for each product, along with their respective categories, names, and prices. The Sales table keeps track of sales, recording a unique identifier (SalesID), the employee responsible, the product category, the sales amount, and the month of sale.
As a sales manager, you frequently need to view detailed sales reports for various purposes. Pulling data from multiple tables involves complex calculations, which could affect runtime efficiency. To simplify this process, create a view using the CREATE VIEW command. This view will display each transaction with the following columns: Sales ID, Employee Name, Category, Sales Amount, and Month.
So, put on your database explorer hat and see if you can find the answer!
Expected output
The expected output is shown below:
Sales ID | Employee Name | Category | Sales Amount | Month |
1 | John | Electronics | 1200 | January |
2 | John | Electronics | 1400 | February |
3 | John | Electronics | 1600 | March |
4 | John | Electronics | 1500 | April |
5 | John | Electronics | 1800 | May |
16 | Emily | Electronics | 300 | January |
6 | Sarah | Cosmetics | 305 | January |
7 | Sarah | Cosmetics | 350 | February |
8 | Sarah | Cosmetics | 405 | March |
9 | Sarah | Cosmetics | 505 | April |
10 | Sarah | Cosmetics | 450 | May |
17 | Emily | Cosmetics | 1000 | January |
11 | Emily | Footwear | 150 | January |
12 | Emily | Footwear | 250 | February |
13 | Emily | Footwear | 300 | March |
14 | Emily | Footwear | 350 | April |
15 | Emily | Footwear | 400 | May |
18 | Emily | Footwear | 3000 | January |
Try it yourself
You can write a query in the following playground:
Hints
Below are some hints to help you understand these concepts better: