[英]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. 因此,我对mySQL有点陌生,可以弄清楚该怎么做。 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.
因此,在此示例中,Paul和Tim都在xxx1中工作,因此该列将说2,但对于John,它将说1,并且他是该房间中的唯一人员。
| 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; 您需要在此处使用count(*)如下:
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 抱歉,刚注意到您正在使用MYSQL,似乎在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.