619_Biggest Single Number

[easy]

Tablenumbercontains many numbers in columnnumincluding duplicated ones. Can you write a SQL query to find the biggest number, which only appears once.

+---+
|num|
+---+
| 8 |
| 8 |
| 3 |
| 3 |
| 1 |
| 4 |
| 5 |
| 6 |

For the sample data above, your query should return the following result:

+---+
|num|
+---+
| 6 |

Note: If there is no such number, just output null.

Solution 1:

SELECT max(a.num) as num
FROM (SELECT num FROM number GROUP BY num HAVING count(*)=1) AS a;

Solution 2:

SELECT (
SELECT num FROM number GROUP BY num HABING count(*) = 1 ORDER BY num desc LIMIT 1
) AS num;

This problem is easy. The only difficult part is if there is no such number, how can we output NULL. One solution is to have a outsider select clause. The other solution is to use max() function such that if there is no input, max() will output NULL.

Last updated