计算以下项的不同值:A列和一对列(A,B)

时间:2018-08-14 15:29:33

标签: sql oracle group-by count oracle12c

假设我们有以下数据:

    +-----------+----------+---------+
    | 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,我们如何计算它有多少 唯一的订单ID ,以及多少对 唯一的对(order_id, line_id)

所需的结果应类似于:

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

3 个答案:

答案 0 :(得分:4)

您可以使用:

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

答案 1 :(得分:4)

不幸的是,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 :(得分:1)

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

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
;