mysql - SQL select count for more than one like

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

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' 

https://stackoverflow.com/questions/11400946/

相关文章:

haskell - 包含不同类型的列表

php - 从php中的日期检索日期,月份,年份

assembly - 为什么我们可以在16位模式下使用eRx,而在32位模式下不能使用rRx?

ruby-on-rails - 仅显示 f.label 覆盖 f.input 标签

sql-server - 普通的 SQL Server 索引是否包含主键值?

php - 如何从一个函数返回多个值

mongodb - 为什么叫NoSQL?

vba - Access 自定义组

sql - 更新引用另一个表

encryption - 解码 AES-256 key 需要多少种组合?