Skip to content
We areTOP 1%

Investments in 2016

MediumLeetCodeSQL: Subqueries & CTEs
Solve on LeetCode(opens in a new tab)
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews
Hint and exampleShow

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

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account