LeetCode 1070: Product Sales Analysis III Solution

Master LeetCode problem 1070 (Product Sales Analysis III), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1070. Product Sales Analysis III

Medium

Problem Explanation

Explanation:

To solve this problem, we need to select the product id, year, quantity, and price for the first year of every product sold. We can achieve this by using a SQL query to join the Sales and Product tables, filter the results to only include the first year of each product, and then display the required columns.

SQL Query:

Solution Code

// SQL query is not directly executable in Java, use JDBC to execute the query
// Make sure to have a JDBC connection and execute the above SQL query
// Here is a basic outline using JDBC:

import java.sql.*;

public class Solution {
    public static void main(String[] args) {
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_db", "username", "password");
            Statement stmt = conn.createStatement();

            String query = "SELECT p.product_id, s.year AS first_year, s.quantity, s.price " +
                    "FROM Sales s " +
                    "JOIN Product p ON s.product_id = p.product_id " +
                    "WHERE (s.product_id, s.year) IN (" +
                    "   SELECT product_id, MIN(year) " +
                    "   FROM Sales " +
                    "   GROUP BY product_id" +
                    ")";

            ResultSet rs = stmt.executeQuery(query);

            while (rs.next()) {
                System.out.println(rs.getInt("product_id") + " " + rs.getInt("first_year") + " " + rs.getInt("quantity") + " " + rs.getInt("price"));
            }

            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1070 (Product Sales Analysis III)?

This page provides optimized solutions for LeetCode problem 1070 (Product Sales Analysis III) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1070 (Product Sales Analysis III)?

The time complexity for LeetCode 1070 (Product Sales Analysis III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1070 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1070 in Java, C++, or Python.

Back to LeetCode Solutions