skip to Main Content

I’m currently working on LeetCode problem 619, "Biggest Single Number," using MySQL. The problem can be found at this link: https://leetcode.com/problems/biggest-single-number/description/

I’ve written a query for this problem, but I’m unable to obtain the correct answer. I suspect that the issue lies with the order of execution in the query. According to the information I found on GeeksforGeeks, the SQL order of execution should be as follows: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> …

Based on this order, I believe the correct sequence should be to first retrieve the data from the MyNumbers table, then group it based on the num column, then select only the numbers that appear exactly once, and finally get the maximum value from the selected numbers.

However, despite following this order of execution, I’m not getting the expected result. I’m wondering what could be going wrong with my approach.

Here’s the query I currently have:

SELECT Max(num)
FROM MyNumbers
GROUP BY num
HAVING COUNT(num) = 1

expect to get the answer of

num
6

while my output is

Max(num)
1
4
5
6

2

Answers


  1. Here’s one way to solve this: select all numbers that only appear once in a subquery, then select the max value from it:

    select max(x.num) as num from (
      select num from MyNumbers group by num having count(*) = 1
    ) x
    
    Login or Signup to reply.
  2. I would be inclined to use an aggregation limit approach here:

    SELECT num
    FROM MyNumbers
    GROUP BY num
    HAVING COUNT(*) = 1
    ORDER BY num DESC
    LIMIT 1;
    

    The aggregation portion of the query will reduce the set to only numbers which appear only once. The LIMIT and ORDER BY logic will return just the largest number from that intermediate set.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search