Count of other rows in table with the same value

前端 未结 2 1257
刺人心
刺人心 2020-12-22 03:37

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 tr

相关标签:
2条回答
  • 2020-12-22 03:56

    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.

    0 讨论(0)
  • 2020-12-22 04:14

    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
    
    0 讨论(0)
提交回复
热议问题