Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT statement to count elements

Tags:

sql

database

I have an SQL table consisting of:

[title]
ElementA
ElementA
ElementB
ElementC
ElementA
ElementA

I am trying to find a way to count the element which occurs the most; in this example, that would be 4 because ElementA has occurred 4 times. The problem is, this table is dynamic, so I can't just say SELECT COUNT(*) WHERE title = 'ElementA';

Does anyone have any idea how to compose a SELECT statement to do this? Conceptually, it seems pretty simple, but I just can't make it work.

Many thanks, Brett

like image 650
Brett Avatar asked Sep 19 '25 03:09

Brett


1 Answers

SELECT TOP 1 Title, COUNT(*) FROM table GROUP BY Title ORDER BY 2 DESC

or

SELECT Title, COUNT(*) FROM table GROUP BY Title ORDER BY 2 DESC LIMIT = 1

depending on the product you're using.

(Edited to correct the ORDER BY clause).

like image 89
Larry Lustig Avatar answered Sep 20 '25 15:09

Larry Lustig