如何计算列中的出现次数,同时包含具有 SQL 的唯一值的另一列?

How to Count Occurrences in a Column while including another column with unique values with SQL?

我有 table 个客户:

id order
0 25
1 25
2 23
3 24
4 25

我想查询所有客户,以及一个计算相同订单号的客户数量的附加列:

id order count
0 25 3
1 25 3
2 21 1
3 25 3
4 22 1

我试过这个语法

SELECT A.id, A.0rder, B.cnt
  FROM Customers  A
  INNER JOIN (
    SELECT Order, count(Order) as cnt
      FROM Customers 
      GROUP BY Order
  ) B ON A.Order = B.Order

和运行进入这个错误。 'Error saving the Query field.Old style JOIN (ANSI JOINs) syntax is not allowed. Please use standard syntax.'

您查询的问题是您名为 order 的列也是一个关键字,例如 ORDER BY。您可以使用 table 别名解决此问题,如下所示:

SELECT 
    A.id, A.order, 
    B.cnt 
FROM 
    Customers A 
INNER JOIN (
  SELECT b.Order, count(b.Order) as cnt 
  FROM Customers b GROUP BY b.Order
) B ON A.Order = B.Order;
id order cnt
0 25 3
1 25 3
2 23 1
3 24 1
4 25 3

View on DB Fiddle

您也可以将 window 函数 COUNT 与订单列上的分区一起使用,或使用相关查询来实现此目的。这两种方法都包含在下面。

查询 #1 - Window 函数

SELECT
    t1.*,
    COUNT(1) OVER (PARTITION BY t1.order) as count
FROM
    my_table t1
ORDER BY 
    t1.id;
id order count
0 25 3
1 25 3
2 23 1
3 24 1
4 25 3

查询 #2

SELECT
    t1.*,
    (
        SELECT COUNT(1) FROM my_table t2 WHERE t2.order=t1.order
    ) as count
FROM
    my_table t1
ORDER BY 
    t1.id;
id order count
0 25 3
1 25 3
2 23 1
3 24 1
4 25 3

View Demo on DB Fiddle

让我知道这是否适合你。