【问题标题】:Aggregation function on Group by on multiple columnsGroup by 多列的聚合函数
【发布时间】:2017-09-16 03:01:26
【问题描述】:
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 计数)然后第 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 行和第 3 行计为一个计数还是两个计数?

【问题讨论】:

    标签: sql oracle group-by aggregation


    【解决方案1】:

    我想你想要count(distinct):

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

    【讨论】:

    • 我认为 count(distinct cid) 是我想要的,但只是好奇我是否按周分组,customer_id,L1 而不是按周分组,customer_id,会有什么不同吗?
    • @Arman 。 . .根据您的样本数据,它会有所作为。
    【解决方案2】:
    SELECT WEEK, 
           CUSTOMER_ID,
           COUNT( DISTINCT CID)
      FROM TABLE
    GROUP BY WEEK,CUSTOMER_ID;
    

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 2013-12-03
      • 1970-01-01
      • 2018-11-07
      相关资源
      最近更新 更多