[英]For each passenger, get the information how many other passengers are in the same cart
I have a table;我有一张桌子;
INSERT INTO passengers(id, name, cart_id)
VALUES (1, Uolevi, 1), (2,Maija, 1), (3, Kaaleppi, 2), (4, Kotivalo, 4), (5, Juustina, 4), (6, Vihtori, 4)
Expected result:预期结果:
| Column A | Column B |
| -------- | -------- |
| Uolevi | 1 |
| Maija | 1 |
| Kaaleppi | 0 |
| Kotivalo | 2 |
| Juustina | 2 |
| Vihtori | 2 |
I used COUNT(*) and GROUP BY cart_id.我使用了 COUNT(*) 和 GROUP BY cart_id。 Then the column Name only shows the first name of each cart_id.然后 Name 列只显示每个 cart_id 的名字。
See http://sqlfiddle.com/#!18/d4b80e/6/0参见http://sqlfiddle.com/#!18/d4b80e/6/0
select
p1.id
,p1.name
,(select count(*) from Passengers p2
where p1.cart_id = p2.cart_id and p1.Id <> p2.Id ) as CountOfOthers
from
Passengers p1
Basically the sub query gets the count of passengers with the same [Passenger.Cart_Id]
excluding themselves.基本上,子查询获取具有相同[Passenger.Cart_Id]
的乘客数量,但不包括他们自己。
Output Output
id name CountOfOthers
1 Uolevi 1
2 Maija 1
3 Kaaleppi 0
4 Kotivalo 2
5 Juustina 2
6 Vihtori 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.