【问题标题】:Counting the instances of customers统计客户的实例
【发布时间】:2010-06-15 15:57:37
【问题描述】:

假设我有一个表,其中有一列名为 CustomerId。 该表的实例示例为:

CustomerId
14
12
11
204
14
204

我想编写一个计算客户 ID 出现次数的查询。 最后,我希望得到这样的结果:

CustomerId      NumberOfOccurences
14              2
12              1
11              1
204             2
14              1

我想不出办法来做到这一点。

【问题讨论】:

  • 这听起来很像家庭作业...如果是,请标记它。
  • 不,不是。我现在正在做一个项目。

标签: sql group-by


【解决方案1】:

这是 GROUP BY 最基本的例子

SELECT CustomerId, count(*) as NumberOfOccurences
    FROM tablex GROUP BY CustomerId;

【讨论】:

    【解决方案2】:

    此页面上的Practice exercise #3 解释了如何执行此操作。

    CREATE TABLE customers
    (   customer_id     number(10)  not null,
        customer_name   varchar2(50)    not null,
        city    varchar2(50),   
        CONSTRAINT customers_pk PRIMARY KEY (customer_id)
    );          
    
    INSERT INTO customers (customer_id, customer_name, city)
    VALUES (7001, 'Microsoft', 'New York');
    
    INSERT INTO customers (customer_id, customer_name, city)
    VALUES (7002, 'IBM', 'Chicago');
    
    INSERT INTO customers (customer_id, customer_name, city)
    VALUES (7003, 'Red Hat', 'Detroit');
    
    INSERT INTO customers (customer_id, customer_name, city)
    VALUES (7004, 'Red Hat', 'New York');
    
    INSERT INTO customers (customer_id, customer_name, city)
    VALUES (7005, 'Red Hat', 'San Francisco');
    
    INSERT INTO customers (customer_id, customer_name, city)
    VALUES (7006, 'NVIDIA', 'New York');
    
    INSERT INTO customers (customer_id, customer_name, city)
    VALUES (7007, 'NVIDIA', 'LA');
    
    INSERT INTO customers (customer_id, customer_name, city)
    VALUES (7008, 'NVIDIA', 'LA');
    

    解决方案:

    以下 SQL 语句将返回 customers 表中每个 customer_name 的不同城市数:

    SELECT customer_name, COUNT(DISTINCT city) as "Distinct Cities"
    FROM customers
    GROUP BY customer_name;
    

    它将返回以下结果集:

    CUSTOMER_NAME   Distinct Cities
    IBM     1
    Microsoft   1
    NVIDIA  2
    Red Hat     3
    

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 2023-03-12
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多