[英]SQL command for distinct values in one column and multiple same values in another
[英]Count Distinct on multiple values within same column in SQL Aggregation
客观的:
我想显示所选组合的不同 ID 的数量。
在下面的示例中,我有粒度级别的数据:ID 级别数据。
我想显示每个组合的不同 ID 的数量。
为此,我使用 count distinct 这将为以下组合提供“1”。
但是假设我想找到同时进行电子商务和面对面交易的 ID 数量,在这种情况下,如果我只使用这些数据,我将显示电子商务和面对面交易的总和,结果将是“2”而不是“1”。
这不仅限于Ecom/Face to face。 我想对所有列应用相同的逻辑。
如果您有任何其他替代方法来解决此问题,请告诉我。
首先在您的表中聚合以获取每个TranType
的不同id
:
SELECT TranType, COUNT(DISTINCT id) counter_distinct
FROM tablename
GROUP BY TranType
然后加入表:
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
或使用相关子查询:
SELECT t1.*,
(SELECT COUNT(DISTINCT t2.id) FROM tablename t2 WHERE t2.TranType = t1.TranType) counter_distinct
FROM tablename t1
但是假设我想找到同时进行电子商务和面对面交易的 ID 数量,在
您可以使用以下方法获取 id 列表:
select id
from t
where tran_type in ('Ecomm', 'Face to face')
group by id
having count(distinct tran_type) = 2;
您可以使用子查询获取计数:
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.