2

table Devices:

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

models table:

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

and query looks this:

 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

what I am getting from that query is:

There are $numOfDevices $model_name items.

and this is OK, but is there a way to count devices only with device_status =3 in the same query?

1 Answer 1

3

Maybe something like this:

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
Sign up to request clarification or add additional context in comments.

7 Comments

SUM(device_status=2) AS device2 don't make it hardier then it is :) The "boolean" returns either 0 or 1, so your CASE WHEN isn't required.
i am getting error: {"errorInfo":["42000",1064,"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM devices\r\n\t\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN models ON models.model_id = devices.type_id\r' at line 4"]}. BTW I'm using PDO and 5.1.62 is the version of mysql
that's fixed error, but (i am sorry) result is not what I really need, I need them bout together (dev3+dev2) + dev3 separatly... i tried SUM(CASE WHEN device_status=2 AND device_status=3 THEN 1 ELSE 0 END) but it doesn't work
OR is the right one: SUM(CASE WHEN device_status=2 OR device_status=3 THEN 1 ELSE 0 END)
@InTry : Updated then answer with a case for both dev3+dev2.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.