mysql - SQL select count for more than one like

标签 mysql sql

如果它是单计数条件,我知道如何让它工作。如何让它适用于多种条件?

SELECT count(TableName.DeviceName where DeviceName like 'AR%' ) as DEVICE_Type_A,
       count(TableName.DeviceName where DeviceName like 'R%' ) as DEVICE_Type_B,
       count(TableName.DeviceName where DeviceName like 'P%' ) as DEVICE_Type_C,
       count(TableName.DeviceName where DeviceName like 'AM%' ) as DEVICE_Type_D,
  FROM DB.TableName TableName
 WHERE TableName.DURATIONMIN > '180'

最佳答案

你应该使用 case 语句!

SELECT count(case when DeviceName like 'AR%' then 1 end) as DEVICE_Type_A,
       count(case when DeviceName like 'R%' then 1 end) as DEVICE_Type_B,
       count(case when DeviceName like 'P%' then 1 end) as DEVICE_Type_C,
       count(case when DeviceName like 'AM%' then 1 end) as DEVICE_Type_D
FROM DB.TableName TableName
WHERE TableName.DURATIONMIN > '180' 

我把计数留在里面了。我个人认为“总和”更清楚:

SELECT sum(case when DeviceName like 'AR%' then 1 else 0 end) as DEVICE_Type_A,
       sum(case when DeviceName like 'R%' then 1 else 0 end) as DEVICE_Type_B,
       sum(case when DeviceName like 'P%' then 1 else 0 end) as DEVICE_Type_C,
       sum(case when DeviceName like 'AM%' then 1 else 0 end) as DEVICE_Type_D
FROM DB.TableName TableName
WHERE TableName.DURATIONMIN > '180' 

关于mysql - SQL select count for more than one like,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11400946/

相关文章:

php - 在 php 中处理 Tinyint

php - QUERY AND ECHO Data INTO HTML INPUT 字段

sql - 松散的 WHERE 语句

mysql - 从第一个 gridview 显示第二个 gridview 的值

mysql - SQL 从具有多个 Where 子句的一个表中进行选择

php - 复杂的数据库设置 : Trying to display two field values that correspond to three other specific fields

sql - 如何在 Postgres 中基于 INSERT RETURNING id 进行 SQL 更新?

mysql - 删除数据库现有记录,同时将值从一行分配给具有唯一值的另一行

php - 'reportes.id_usuario' 中的未知列 'on clause'

sql - 带有未定义类型的 Case 语句?或为什么约会?