简体   繁体   English

对于每位乘客,获取同一购物车中有多少其他乘客的信息

[英]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.

相关问题 SQL:获取每个分组中的最新条目以及每个分组中有多少条目 - SQL: Get both the newest entry from each grouping as well as how many there are in each group 如何比较数组中的每个元素并计算Python中相同元素的百分比? - How to compare each element in array and calculate percentage of how many are the same in Python? 如何列出同一表的多个列的值,并计算在mysql中每个列重复这些值多少次? - How to list values of multiple columns of the same table and count how many times these values are repeated for each column in mysql? 如何计算 Java 脚本数组中的项目,但仅当项目彼此相邻时? - How can I count items in Java Script array but only when items are the same next to each other? 统计每个ID有多少个变量 - Count for each ID how many variables 如何计算每个GroupBy&#39;d行(SQL Server)中包含的“累计”行数? - How can I get the count for how many rows were “rolled up” to be included in each GroupBy'd row (SQL Server)? 为了获得语料库的前k个单词,我们必须从每个文本文件中选择多少个最重要的单词 - How Many Top Words We Have to Select from Each Text File in Order to Get the Top k Words of the Corpus 如何计算每个患者预订了多少名医生? - How to count how many doctors are booked by each patient? 使用LIKE子句计算每个外键有多少条记录 - Count how many records there are for each foreign key, with LIKE clause 如何在多对多关系中获得总数? - How can I get the total in a many to many relationship?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM