2

表设备:

id   device type_id device_status
1     dev1     2        1         
2     dev2     2        2        
3     dev3     7        2         
4     dev5     9        3         

型号表:

model_id vendor_id model_name
  1        3          name1          
  2        5          name2       
  3        7          name3         
  4        7          name4 

查询看起来像这样:

 SELECT model_id, type_id, model_name,
 COUNT(type_id) AS numOfDevices
 FROM devices
 LEFT JOIN models ON models.model_id = devices.type_id
 WHERE device_status = 2 OR device_status = 3
 GROUP BY type_id

我从该查询中得到的是:

There are $numOfDevices $model_name items.

这没关系,但是有没有办法在同一个查询中只计算 device_status =3 的设备?

4

1 回答 1

3

也许是这样的:

SELECT model_id, type_id, model_name,
 SUM(CASE WHEN device_status=2 THEN 1 ELSE 0 END) AS device2,
 SUM(CASE WHEN device_status=3 THEN 1 ELSE 0 END) AS device3,
 SUM(CASE WHEN device_status IN (2,3) THEN 1 ELSE 0 END) AS device2device3
 FROM devices
 LEFT JOIN models ON models.model_id = devices.type_id
 WHERE device_status = 2 OR device_status = 3
 GROUP BY type_id
于 2012-05-02T11:01:49.887 回答