Sponsored
Sponsored
We will use an SQL query with an INNER JOIN to combine the Sales and Product tables based on the product_id. INNER JOIN will ensure we fetch records that have corresponding IDs in both tables. After joining, we will project the columns product_name, year, and price.
Time Complexity: O(N) where N is the number of rows in Sales table.
Space Complexity: O(1) as we use a fixed amount of extra space for the query execution.
1SELECT P.product_name, S.year, S.price FROM Sales S INNER JOIN Product P ON S.product_id = P.product_id;
This SQL query selects the product_name from the Product table and year and price from the Sales table. We use INNER JOIN
to join these two tables based on product_id
.
This approach involves using programming constructs to emulate a join operation typically done in SQL. We'll utilize hash maps (or dictionaries) in different languages to store data from one table and then iterate through the other to join and construct the result.
Time Complexity: O(N + M) where N is the number of products and M is the number of sales.
Space Complexity: O(N) to store the dictionary mapping product_id to product_name.
1#include <unordered_map>
2#include <vector>
3#include <string>
4#include <iostream>
5using namespace std;
struct Sale {
int sale_id;
int product_id;
int year;
int quantity;
int price;
};
struct Product {
int product_id;
string product_name;
};
struct Result {
string product_name;
int year;
int price;
};
vector<Result> productSalesAnalysis(vector<Sale>& sales, vector<Product>& products) {
unordered_map<int, string> productMap;
for (const auto& product : products) {
productMap[product.product_id] = product.product_name;
}
vector<Result> result;
for (const auto& sale : sales) {
if (productMap.find(sale.product_id) != productMap.end()) {
result.push_back({productMap[sale.product_id], sale.year, sale.price});
}
}
return result;
}
int main() {
vector<Sale> sales = {
{1, 100, 2008, 10, 5000},
{2, 100, 2009, 12, 5000},
{7, 200, 2011, 15, 9000}
};
vector<Product> products = {
{100, "Nokia"},
{200, "Apple"},
{300, "Samsung"}
};
vector<Result> results = productSalesAnalysis(sales, products);
for (const auto& result : results) {
cout << result.product_name << " " << result.year << " " << result.price << endl;
}
return 0;
}
In C++, we leverage an unordered_map
to quickly retrieve product names using product_id
as the key. We iterate over the sales data, find the matching product name using our map, and store the necessary details in a result vector.