mysql - 获取所有行的计数指定不同的 where 子句

标签 mysql database

我有一个简单的表,其中有一列id。该列不是主键(PK)。 id 的值可以在 1 到 10 之间。我想编写一个查询,给出单个表中所有数字的计数,如下所示:

one   two three four ............
 5     8    9     15 ...........

我知道我可以编写这样的查询:select count(*) from table where id = 1。但这返回给我的是单个数字计数意味着id =1。我需要在单个查询中编写一个查询 1 到 10 之间的所有数字的查询。

最佳答案

带旋转

大致如下:

select 
count(case when id= 1 then 1 end) One,
count(case when id= 2 then 1 end) Two,
count(case when id= 3 then 1 end) Three,
count(case when id= 4 then 1 end) Four,
count(case when id= 5 then 1 end) Five,
count(case when id= 6 then 1 end) Six,
count(case when id= 7 then 1 end) Seven,
count(case when id= 8 then 1 end) Eight,
count(case when id= 9 then 1 end) Nine,
count(case when id= 10 then 1 end) Ten
from data;

结果:

ONE TWO  THREE  FOUR    FIVE    SIX SEVEN   EIGHT   NINE    TEN
4   1      0      0       0       0    0      0        0    1

SQLFiddle Demo

不旋转

您可以使用以下内容:

select id, count(*) as Count from data group by id;

结果将显示为:

id, count
1            5 
2            8
3            9
4            15

关于mysql - 获取所有行的计数指定不同的 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17876389/

相关文章:

mysql - 按下一个和上一个排序

php - MySQL 中带有加法运算符的 IF/ELSE 语句

database - GUID 与 int ID 自动递增

database - 多值依赖公理

mysql - MYSQL 数据库和表大小有限制吗

php - 允许用户在 mysql 中编辑

MYSQL嵌套内连接查询

mysql - 选择在一个日期存在但在另一个日期不存在的记录?

python - Django:快速检索 manyToMany 字段的 ID

sql - 使用连接查询从四个不同的表中获取记录