计算客户的实例

时间:2010-06-15 15:57:37

标签: sql group-by

假设我有一个名为CustomerId的列的表。 该表的实例示例如下:

CustomerId
14
12
11
204
14
204

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

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

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

2 个答案:

答案 0 :(得分:10)

这是GROUP BY的最基本的例子

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

答案 1 :(得分:1)

此页面上的

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