简体   繁体   中英

Count Distinct on multiple values within same column in SQL Aggregation

Objective:

I wanted to show the number of distinct IDs for any combination selected.

In the below example, I have data at a granular level: ID level data.

I wanted to show the number of distinct IDs for each combination.

For this, I use count distinct which will give me '1' for the below combinations.

But let's say if I wanted to find the number of IDs who made both E-commerce and Face to face transactions, in that case, if I just use this data, I would be showing the sum of E-comm and Face to face and the result would be '2' instead of '1'.

And this is not limited to Ecom/Face to face. I wanted to apply the same logic for all columns.

Please let me know if you have any other alternative approach to address this issue.

First aggregate in your table to get the distinct id s for each TranType :

SELECT TranType, COUNT(DISTINCT id) counter_distinct
FROM tablename
GROUP BY TranType

and then join to the table:

SELECT t.*, g.counter_distinct
FROM tablename t 
INNER JOIN (
  SELECT TranType, COUNT(DISTINCT id) counter_distinct
  FROM tablename
  GROUP BY TranType
) g ON g.TranType = t.TranType

Or use a correlated subquery:

SELECT t1.*, 
       (SELECT COUNT(DISTINCT t2.id) FROM tablename t2 WHERE t2.TranType = t1.TranType) counter_distinct
FROM tablename t1

But let's say if I wanted to find the number of IDs who made both E-commerce and Face to face transactions, in

You can get the list of ids using:

select id
from t
where tran_type in ('Ecomm', 'Face to face')
group by id
having count(distinct tran_type) = 2;

You can get the count using a subquery:

select count(*)
from (select id
      from t
      where tran_type in ('Ecomm', 'Face to face')
      group by id
      having count(distinct tran_type) = 2
     ) i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM