繁体   English   中英

表中其他具有相同值的行的计数

[英]Count of other rows in table with the same value

因此,我对mySQL有点陌生,可以弄清楚该怎么做。 我有一张桌子,上面有工作人员的柱子,工作的建筑物以及工作的办公室。

我正在尝试进行查询,该查询将返回此表并带有额外的列,该列表示在同一房间中有多少人工作。 因此,在此示例中,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               |

尝试这个:

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

我建议您不要在字段名中使用空格,而应使用下划线代替空格。

这类问题可以通过解析函数解决。

因此,在这里了解一下解析函数。

您需要在此处使用count(*)如下:

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

编辑

抱歉,刚注意到您正在使用MYSQL,似乎在MYSQL上没有可用的分析函数

所以试试这个;

   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.

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