计算有多少行具有相同的值

时间:2013-05-23 07:14:36

标签: mysql sql

如何编写SQL查询来计算表格num列中特定num值的总数。

e.g。选择num = 1

的位置

结果:2

+-----+-----+
| NAME | NUM |
+=====+=====+
| SAM  |  1  | 
+-----+-----+
| BOB  |  1  |
+-----+-----+
| JAKE |  2  | 
+-----+-----+  
| JOHN |  4  | 
+-----+-----+

8 个答案:

答案 0 :(得分:96)

尝试

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

SQL FIDDLE

答案 1 :(得分:14)

如果您想获得NUM的所有值的结果:

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

或仅针对一个特定的:

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

答案 2 :(得分:13)

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

答案 3 :(得分:7)

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

答案 4 :(得分:3)

尝试此查询

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

<强> SQL FIDDLE

答案 5 :(得分:1)

SELECT sum(num) WHERE num = 1;

答案 6 :(得分:1)

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

e.g。为您查询: -

Selector(("handleGetURLEvent:replyEvent:"))

答案 7 :(得分:-2)

使用此查询,将给出您的输出:

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