【问题标题】:counting the distinct values of: a column A and the pair of columns (A,B)计算不同的值:A列和一对列(A,B)
【发布时间】:2018-08-14 15:29:33
【问题描述】:

假设我们有以下数据:

    +-----------+----------+---------+
    | user_code | order_id | line_id |
    +-----------+----------+---------+
    | ezz       | 1        | 1       |
    +-----------+----------+---------+
    | ezz       | 1        | 2       |
    +-----------+----------+---------+
    | ezz       | 1        | 2       |
    +-----------+----------+---------+
    | ezz       | 2        | 1       |
    +-----------+----------+---------+
    | ezz       | 2        | 2       |
    +-----------+----------+---------+
    | ezz       | 2        | 2       |
    +-----------+----------+---------+
    | ezz       | 2        | 2       |
    +-----------+----------+---------+
    | ezz       | 2        | 3       |
    +-----------+----------+---------+
    | ezz       | 3        | 1       |
    +-----------+----------+---------+

对于给定的user_code,我们如何计算它有多少 unique order_id 以及有多少 unique pair (order_id, line_id) 有吗?

所需的结果应如下所示:

+-----------+-------------+------------------+
| user_code | order_count | order_line_count |
+-----------+-------------+------------------+
| ezz       | 3           | 6                |
+-----------+-------------+------------------+

【问题讨论】:

  • @JuanCarlosOropeza:甲骨文 12c

标签: sql oracle group-by count oracle12c


【解决方案1】:

不幸的是,Oracle 不支持count(distinct) 带有多个参数。您可以使用字符串连接:

select user_code, count(distinct order_id) as num_orders,
       count(distinct order_id || ':' || line_id) as num_order_lines
from t
group by user_code;

【讨论】:

    【解决方案2】:

    你可以使用:

    SELECT user_code,
         COUNT(DISTINCT order_id) AS order_count,
         COUNT(DISTINCT order_id || '^' || line_id) AS order_line_count
                        -- building single value from 2 columns
    FROM tab
    GROUP BY user_code
    

    【讨论】:

      【解决方案3】:

      一种方法是先对数据进行重复数据删除,然后使用计数(不同)和标准计数。

      select   user_code, count(distinct order_id) as ct_ord_id, 
                          count(line_id)           as ct_line_id
      from     (select distinct user_code, order_id, line_id from TABLE_NAME)
      group by user_code
      ;
      

      【讨论】:

        猜你喜欢
        • 2020-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 2011-12-23
        • 1970-01-01
        • 2019-05-16
        相关资源
        最近更新 更多