如何计算(distinct [columnname])在同一列的不同行中满足两个条件的情况?

时间:2016-01-22 19:22:39

标签: sql

我试图计算AccountNumbers whereInterestTypeWebsite Phone SELECT count(distinct c.[AccountNumber]) AS [TriangleSize] FROM table WHERE [InterestType] = 'Web' 中的AccountNumber计数另一排。

现在我有以下查询:

InterestType

我只需要在给定的InterestType只计算AccountNumber InterestType 001 Web 001 Phone 002 Web 002 Catalog 002 Mail 003 Phone 004 Phone 004 Web 'Web'某处且[TriangleSize] 2 '电话'某处的情况下才能进行此查询。

示例:

{{1}}

如果这些是数据库中的行,我的理想查询将返回:

{{1}}

2 个答案:

答案 0 :(得分:2)

SELECT COUNT(DISTINCT T1.AccountNumber)
FROM
    My_Table T1
INNER JOIN My_Table T2 ON
    T2.AccountNumber = T1.AccountNumber AND
    T2.InterestType = 'Web'
WHERE
    T1.InterestType = 'Phone'

答案 1 :(得分:1)

如果您需要帐号:

SELECT c.[AccountNumber]
FROM table c
WHERE [InterestType] IN ('Web', 'Phone')
GROUP BY c.[AccountNumber]
HAVING COUNT(*) = 2;

如果要计算它们,请使用子查询:

SELECT COUNT(*)
FROM (SELECT c.[AccountNumber]
      FROM table c
      WHERE [InterestType] IN ('Web', 'Phone')
      GROUP BY c.[AccountNumber]
      HAVING COUNT(*) = 2
     ) a;

或者,可能是最有效的版本:

select count(*)
from table c
where InterestType = 'Web' and
      exists (select 1
              from table c2
              where c2.AccountNumber = c.AccountNumber and
                    c2.InterestType = 'Phone'
             );

这很好,因为没有count(distinct),因为不应该有重复项(除非可以为给定帐户复制兴趣类型)。