Count how many rows have the same value

MysqlSql

Mysql Problem Overview


How do I write an SQL query to count the total number of a specific num value in the num column of a table?

Assuming we have the following data.

NAME NUM
SAM 1
BOB 1
JAKE 2
JOHN 4

Take the following query:

SELECT WHERE num = 1;

This would return these two rows.

NAME NUM
SAM 1
BOB 1

Mysql Solutions


Solution 1 - Mysql

Try

SELECT NAME, count(*) as NUM FROM tbl GROUP BY NAME

SQL FIDDLE

Solution 2 - Mysql

If you want to have the result for all values of NUM:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
GROUP BY `NUM`

Or just for one specific:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
WHERE `NUM`=1

Solution 3 - Mysql

FOR SPECIFIC NUM:

SELECT COUNT(1) FROM YOUR_TABLE WHERE NUM = 1

FOR ALL NUM:

SELECT NUM, COUNT(1) FROM YOUR_TABLE GROUP BY NUM

Solution 4 - Mysql

SELECT 
   COUNT(NUM) as 'result' 
FROM 
   Table1 
GROUP BY 
   NUM 
HAVING NUM = 1

Solution 5 - Mysql

Try this Query

select NUM, count(1) as count 
from tbl 
where num = 1
group by NUM
--having count(1) (You condition)

SQL FIDDLE

Solution 6 - Mysql

SELECT sum(num) WHERE num = 1;

Solution 7 - Mysql

SELECT SUM(IF(your_column=3,1,0)) FROM your_table WHERE your_where_contion='something';

e.g. for you query:-

SELECT SUM(IF(num=1,1,0)) FROM your_table_name;

Solution 8 - Mysql

Use this query this will give your output:

select 
  t.name
  ,( select 
       count (*) as num_value 
     from Table 
      where num =t.num) cnt 
from Table t;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2273278View Question on Stackoverflow
Solution 1 - MysqlMeherzadView Answer on Stackoverflow
Solution 2 - MysqlSirkoView Answer on Stackoverflow
Solution 3 - MysqlDhwaniView Answer on Stackoverflow
Solution 4 - MysqlDeval ShahView Answer on Stackoverflow
Solution 5 - MysqlPrahalad GaggarView Answer on Stackoverflow
Solution 6 - Mysql0xAliView Answer on Stackoverflow
Solution 7 - Mysqluser8567224View Answer on Stackoverflow
Solution 8 - MysqlRohit SahuView Answer on Stackoverflow