【问题标题】:multiple counts多次计数
【发布时间】:2020-07-27 13:07:57
【问题描述】:

我有这张桌子:

user product log_date 

1    aaa     02-02-2020
2    aaa     05-01-2020
1    aaa     03-02-2020
2    aaa     06-01-2020
3    ccc     09-08-2020

我想查询这个

product total_entries  total_users
aaa     4              2
ccc     1              1

我这样做了:

SELECT 
 product,
 count(*) total_entries,
 count(*) over(partition by product,user ) total_users
from table 
group by product; 

我收到这个错误

ORA-00979: not a GROUP BY expression

有什么帮助吗?

【问题讨论】:

    标签: sql oracle group-by count


    【解决方案1】:
    with t(userid, product, log_date ) as (
    select 1,    'aaa',     '02-02-2020' from dual union all
    select 2,    'aaa',     '05-01-2020' from dual union all
    select 1,    'aaa',     '03-02-2020' from dual union all
    select 2,    'aaa',     '06-01-2020' from dual union all
    select 3,    'ccc',     '09-08-2020' from dual
    )
    select product, count(*) total_entries, count(distinct userid) total_users
    from t
    group by product;
    
    PRODUCT TOTAL_ENTRIES TOTAL_USERS
    ------- ------------- -----------
    ccc                 1           1
    aaa                 4           2
    

    【讨论】:

      【解决方案2】:

      试试这个:

      SELECT 
      product,
      count(*) OVER (partition by product) total_entries,
      count(*) over(partition by product,user ) total_users
      from table; 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-16
        • 2015-06-03
        相关资源
        最近更新 更多