SQL选择计数多于一个

时间:2012-07-09 18:28:56

标签: 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'

2 个答案:

答案 0 :(得分:7)

您应该使用案例陈述!

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' 

答案 1 :(得分:1)

您应该使用子选择:

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