2016-01-22 43 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。 。 。其次應該計算符合您的條件的帳戶數量(包括網絡和電話)。這不是你想要的嗎? –

相關問題