![](/img/trans.png)
[英]Count how many rows have the same value but if the ID are different count it separate
[英]Count how many rows with the same value
我有以下表格:
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 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
我在帶有表 A 的 Enterpr_id 上有一個外鍵,如何進行計數並獲得預期的輸出:
Nespresso - 2 users
what - 1 user
else - 1 user
need - 1 user
help - 0 user
這是一個簡單的連接:
select a.user, b.name
from tablea a
inner join tableb b on b.entrepr_id = a.entrepr_id
編輯:從您更新的問題來看,您似乎想要聚合和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
這是一個帶有計數的左連接查詢:
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.