2

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

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'
4

2 回答 2

11

你应该使用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' 
于 2012-07-09T18:50:02.237 回答
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'
于 2012-07-09T18:32:38.597 回答