Investments in 2016
MediumLeetCodeSQL: Subqueries & CTEs
Hint and exampleShowHide
Write each condition as a grouped subquery, HAVING COUNT(*) > 1 for a value shared with another row and HAVING COUNT(*) = 1 for a unique pair of columns, and filter with IN.
Example: students(id, grade, city, school, prize)
id | grade | city | school | prize
1 | A | Pune | S1 | 10
2 | A | Delhi | S2 | 20
3 | B | Pune | S1 | 30
4 | C | Goa | S3 | 40
SELECT SUM(prize) AS total
FROM students
WHERE grade IN (SELECT grade FROM students
GROUP BY grade HAVING COUNT(*) > 1)
AND (city, school) IN (SELECT city, school FROM students
GROUP BY city, school HAVING COUNT(*) = 1);
-- only id 2 has a shared grade and a unique (city, school): total = 20
More in SQL: Subqueries & CTEs
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | Customers Who Never Order | LeetCode | Easy | Solve Customers Who Never Order on LeetCode (opens in a new tab) | |||
| 2 | Second Highest Salary | LeetCode | Medium | Solve Second Highest Salary on LeetCode (opens in a new tab) | |||
| 3 | Department Highest Salary | LeetCode | Medium | Solve Department Highest Salary on LeetCode (opens in a new tab) | |||
| 4 | Customers Who Bought All Products | LeetCode | Medium | Solve Customers Who Bought All Products on LeetCode (opens in a new tab) | |||
| 5 | Investments in 2016 | LeetCode | Medium | Solve Investments in 2016 on LeetCode (opens in a new tab) |