简体   繁体   English

在 SQL 聚合中的同一列中的多个值上计数不同

[英]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.我想显示所选组合的不同 ID 的数量。

In the below example, I have data at a granular level: ID level data.在下面的示例中,我有粒度级别的数据:ID 级别数据。

I wanted to show the number of distinct IDs for each combination.我想显示每个组合的不同 ID 的数量。

For this, I use count distinct which will give me '1' for the below combinations.为此,我使用 count distinct 这将为以下组合提供“1”。

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'.但是假设我想找到同时进行电子商务和面对面交易的 ID 数量,在这种情况下,如果我只使用这些数据,我将显示电子商务和面对面交易的总和,结果将是“2”而不是“1”。

And this is not limited to Ecom/Face to face.这不仅限于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 :首先在您的表中聚合以获取每个TranType的不同id

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但是假设我想找到同时进行电子商务和面对面交易的 ID 数量,在

You can get the list of ids using:您可以使用以下方法获取 id 列表:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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