I have a table which has no primary key and I can’t add one – the relevant columns from it are:
Department | Category |
-------------+-----------+
0001 | A |
0002 | D |
0003 | A |
0003 | A |
0003 | C |
0004 | B |
I want to retrieve a single row for each Department, which gives me the department code and the Category which appears most frequently in the table, i.e.
Department | Category |
-------------+-----------+
0001 | A |
0002 | D |
0003 | A |
0004 | B |
What is the best way to achieve this? My current attempt involves a Count(Category) in a subquery from which the Max(CountofCategory) is then taken, but including the Category field at this stage means too many rows at returned (since GROUP BY is applied at Category level as well as Department). In the case of a tie, I’d just select the min/max of the category arbitrarily. Ideally this should be database-agnostic, but is likely to run on either Oracle or MySQL.
Works in both Oracle and SQL Server, I believe is all standard SQL, from later standards:
EDIT I don’t know why I used the WITH, the solution is probably easier to read using an inline view:
END EDIT
Test cases: