简体   繁体   中英

Count of other rows in table with the same value

So I'm a bit new to mySQL and can figure out how to do this. I have a table with columns for worker, the building they work in, and the office they work in.

I'm trying to make query that will return this table with an extra column saying how many people work in the same room. so in this example Paul and Tim both work in xxx1 and so the column would say 2 but for John it would say 1 and he's the only person in that room.

| worker | office building   | room number     |
------------------------------------------------
| john   | xxx               | 0               | 
| paul   | xxx               | 1               |
| tim    | xxx               | 1               |
| Dave   | yyy               | 0               |    
| Ty     | yyy               | 1               |    
| Luke   | yyy               | 1               |

Try this:

SELECT t1.*,
  (SELECT COUNT(1)
  FROM mytable t2
  WHERE t2.`room number` = t1.`room number`
  )
FROM mytable t1

I advice you don't use field name with white space, use the underscore instead white space.

These sort of problems are solved with analytic functions.

So have a look at here about analytic functions.

What you need here is to use count(*) over as follows;

select  t.*, count(1) OVER (PARTITION BY office_building, room_number) from t

EDIT

Sorry, just noticed you are working on MYSQL, seems like no analytical functions available on MYSQL

So try this;

   select t.*, wcounts.worker_count 
   from t,
   (select office_building, room_number count(1) as worker_count
      from t
     group by office_building, room_number) wcounts
   where t.office_building = wcounts.office_building
   and t.room_number = wcounts.room_number

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