Skip to content
Advertisement

SQL query for counting the number of same values in a table and fetching the first value if the count is greater than 1

There is a table such as

+-----+-------+
| id  | status|
+-----+-------+
| 01  | open  |
| 02  | close |
| 03  | close |
| 04  | close |
| 05  | open  |
| 06  | open  |
| 07  | open  |
| 08  | close |
| 09  | open  |
| 10  | close |
+-----+-------+

I want the number of open-status records and if the number of records are greater than 1, I want to fetch the 1st open status record ID.

for that, I have been trying doing like this

SELECT status, count(*) as count from table_name group by status='open' order by status desc limit 1
if(@count>0)
select * from table_name where status like 'open' union select * from table_name limit 1

which seems not working (please forgive me if it is a blunder).

I finally want the ID of the first open-status record if only the number of open status records is more than 1.

Advertisement

Answer

you can use a query like this:

SELECT STATUS, count(*) AS count, MIN(id) AS FirstID
FROM TABLE_NAME
WHERE STATUS = 'open'
GROUP BY STATUS
HAVING count(*) > 1;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement