简体   繁体   中英

how to get total and total of subset using mysql?

I am trying to have a mysql query return a calculated result, but am having some challenges as I am only able to get it to return 1 value.

http://sqlfiddle.com/#!9/5e9276/1

Is it possible to get total count for agents that are robot types within a department, and then the total of agents within department to calculate %?

example: department 1, has 4 out of 5 robots. (80% robots)

the type field may not always have the same value, but will contain at least the keyword 'robot' or 'human'.

I know I can get the % programmatically, but wanted to check if there was a way to do this directly using mysql query.

Any help is appreciated.

Thanks,

Maybe this is what you want:

SELECT 
  department, 
  SUM(type LIKE '%robot%') robots, 
  COUNT(department) total, 
  SUM(type LIKE '%robot%') / COUNT(department) robot_percentage
FROM agents
GROUP BY department;

Example SQL Fiddle

To format the robot_percentage with percent sign you coud do:

CONCAT(FORMAT( (SUM(type LIKE '%robot%')*100 / COUNT(department)),2),'%') robot_percentage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM