簡體   English   中英

計算以下項的不同值:A列和一對列(A,B)

[英]counting the distinct values of: a column A and the pair of columns (A,B)

假設我們有以下數據:

    +-----------+----------+---------+
    | 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 ,我們如何計算它具有多少個唯一的order_id以及它具有多少個唯一對(order_id,line_id)

所需的結果應類似於:

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

您可以使用:

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

不幸的是,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;

一種方法是先對數據進行重復數據刪除,然后使用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
;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM