多列上的Group by聚合函数

时间:2017-04-19 18:14:54

标签: sql oracle group-by aggregation

WEEK    | CID | CUSTOMER_ID | L1
2017-04 | 12  | 1           | ABC
2017-04 | 13  | 1           | ABC
2017-04 | 13  | 1           | ABC
2017-04 | 16  | 1           | DFG
2017-04 | 15  | 2           | DFG
2017-14 | 14  | 1           | DFG

我通过组合许多数据库创建了一个表(上面创建的表的示例)。我希望每个customer_id每周进入的次数(这样,2017-04customer_id 1就像3次一样,我们要将第2行和第3行视为相同(因此对于然后第1行和第4行使它成为3次。

所以,输出应该是:

WEEK    | CUSTOMER_ID | COUNT(CUSTOMER_ID)
2017-04 | 1           | 3
2017-04 | 2           | 1
2017-14 | 1           | 1

我正在尝试以下几行:

select
    week, customer_id, count(customer_id)
from
    table
group by 
    week, cid, customer_id, L1;

但是,我想确认这样做会计算第2行和第2行吗? 3作为一个或两个计数?

2 个答案:

答案 0 :(得分:2)

我想你想要count(distinct)

select week, customer_id, count(distinct cid)
from table
group by week, customer_id;

答案 1 :(得分:0)

SELECT WEEK, 
       CUSTOMER_ID,
       COUNT( DISTINCT CID)
  FROM TABLE
GROUP BY WEEK,CUSTOMER_ID;