2016-01-22 79 views
0

我试图让AccountNumbers在所有whereInterestType他们在WebsitePhone列在其他行。如何在同一列的不同行中满足两个条件的情况下进行计数(distinct [columnname])?

现在我有以下查询:

SELECT 
    count(distinct c.[AccountNumber]) AS [TriangleSize] 
    FROM table 
    WHERE [InterestType] = 'Web' 

我需要这个查询只能在那里,如果它有InterestType“网络”的地方,并InterestType“电话”的地方给定AccountNumber只计算。

例子:

AccountNumber InterestType 
001    Web 
001    Phone 
002    Web 
002    Catalog 
002    Mail 
003    Phone 
004    Phone 
004    Web 

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

[TriangleSize] 
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

如果你想在账户号码:

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)因为应该没有重复(除非给定帐户的兴趣类型可以重复)。

+0

这几乎工作,但我认为有一个DISTINCT丢失的地方。这完全来自'电话'和'网络'的数字 – Doomsy

+0

@doomsy。 。 。其次应该计算符合您的条件的帐户数量(包括网络和电话)。这不是你想要的吗? –

相关问题