简体   繁体   English

计算具有相同值的行数

[英]Count how many rows with the same value

I have the following tables:我有以下表格:

Table A:

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   ID  |   User    |   Enterpr_id    |
|   1   |   test1   |      1          |
|   2   |   test2   |      2          |
|   3   |   test3   |      3          |
|   4   |   test4   |      4          |
|   5   |   test5   |      1          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Table B:

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Enterpr_id    |     Name    |
|   1             |   Nespresso |
|   2             |     what    |
|   3             |     else    |
|   4             |     need    |
|   5             |     help    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

I have a foreign key on Enterpr_id with Table A, how can I make a count alternate and get the expected Output:我在带有表 A 的 Enterpr_id 上有一个外键,如何进行计数并获得预期的输出:

Nespresso - 2 users
what - 1 user
else - 1 user
need - 1 user
help - 0 user

That's a simple join:这是一个简单的连接:

select a.user, b.name
from tablea a
inner join tableb b on b.entrepr_id = a.entrepr_id

Edit : from your updated question, you seem to want aggregation and a left join :编辑:从您更新的问题来看,您似乎想要聚合和left join

select b.name, count(a.id) cnt_users
from tableb b
left join tablea a on a.entrepr_id = b.entrepr_id 
group by b.entrepr_id, b.name
order by b.entrepr_id 

It's a left join query with a count:这是一个带有计数的左连接查询:

SELECT Name, COUNT(TableA.ID)
FROM TableB LEFT JOIN TableA ON TableB.Enterpr_id = TableA.Enterpr_id
GROUP BY TableB.Enterpr_id, TableB.Name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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