86

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

假设我们有以下数据。

姓名 NUM
山姆 1
鲍勃 1
杰克 2
约翰 4

进行以下查询:

SELECT WHERE num = 1;

这将返回这两行。

姓名 NUM
山姆 1
鲍勃 1
4

8 回答 8

146

尝试

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

SQL 小提琴

于 2013-05-23T07:15:42.183 回答
19

如果你想得到所有值的结果NUM

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

或者只是针对一个特定的:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
WHERE `NUM`=1
于 2013-05-23T07:15:47.277 回答
16

对于特定号码:

SELECT COUNT(1) FROM YOUR_TABLE WHERE NUM = 1

对于所有号码:

SELECT NUM, COUNT(1) FROM YOUR_TABLE GROUP BY NUM
于 2013-05-23T07:16:02.693 回答
12
SELECT 
   COUNT(NUM) as 'result' 
FROM 
   Table1 
GROUP BY 
   NUM 
HAVING NUM = 1
于 2013-05-23T07:20:05.917 回答
5

试试这个查询

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

SQL 小提琴

于 2013-05-23T07:19:10.560 回答
2
SELECT sum(num) WHERE num = 1;
于 2013-05-23T07:18:56.693 回答
2

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

例如为您查询:-

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

于 2017-09-06T06:14:41.250 回答
-3

使用此查询,这将提供您的输出:

select 
  t.name
  ,( select 
       count (*) as num_value 
     from Table 
      where num =t.num) cnt 
from Table t;
于 2020-02-16T17:20:37.437 回答