I'm looking for a way to select the most occurring value, e.g. the person who posted most for each thread;
SELECT MOST_OCCURRING(user_id) FROM thread_posts GROUP BY thread_id
Is there a good way to do this?
I'm looking for a way to select the most occurring value, e.g. the person who posted most for each thread;
SELECT MOST_OCCURRING(user_id) FROM thread_posts GROUP BY thread_id
Is there a good way to do this?
There's numerous examples if you check the questions under the "greatest n per group" tag. But in this case, you don't define how you want to handle ties - what if two or more users have the same count value?
If you want a count on a per thread basis, I think you can use a nested query; grouping by thread first and then by user:
This will tabulate the occurrences of user_id per thread
But you only wish to select the top user for each thread
which is equivalent to
The HAVING keyword is usually used with an aggregation operation to cherry-pick the aggregated output lines that satisfy the conditions in the HAVING clause.
The HAVING clause is different from the the WHERE clause, wherein the HAVING clause filters resultant output of a query. Whereas, the WHERE clause filters on the input data of a query. Since theHAVING clause filters the resultant output of a query, it must appear after the ORDER BY and GROUP BY clauses.