In MySQL (which I assume you are using since you sent SELECT *, COUNT(*) FROM T GROUP BY X Which failed in all the RDBMS I know of). You can use:
SELECT T.* FROM T INNER JOIN ( SELECT X, COUNT(*) AS Records FROM T GROUP BY X ORDER BY Records DESC LIMIT 1 ) T2 ON T2.X = TX
This has been tested in MySQL and removes implicit grouping / aggregation.
If you can use window functions and one of TOP / LIMIT with Ties or Common Table expressions, it gets even shorter:
Window function + CTE: (MS SQL-Server and PostgreSQL Tested)
WITH CTE AS ( SELECT *, COUNT(*) OVER(PARTITION BY X) AS Records FROM T ) SELECT * FROM CTE WHERE Records = (SELECT MAX(Records) FROM CTE)
Window function with TOP (MS SQL-Server Tested)
SELECT TOP 1 WITH TIES * FROM ( SELECT *, COUNT(*) OVER(PARTITION BY X) [Records] FROM T ) ORDER BY Records DESC
Finally, I never used the oracle, so I did not add a solution that works on oracle ...
EDIT
My MySQL solution did not take into account the connection, and my proposal for solving this kind of steps on the fingers of what you said you want to avoid (duplicate subqueries), so I'm not sure I can help after everything, but just in case, the version is preferable here , which will work as needed on your violin:
SELECT T.* FROM T INNER JOIN ( SELECT X FROM T GROUP BY X HAVING COUNT(*) = ( SELECT COUNT(*) AS Records FROM T GROUP BY X ORDER BY Records DESC LIMIT 1 ) ) T2 ON T2.X = TX
source share