簡體   English   中英

我如何在同一列的不同行中滿足兩個條件的地方計算(distinct [columnname])?

[英]How do I count(distinct [columnname]) where TWO conditions are met in different rows of the same column?

我試圖獲得的計數AccountNumbers在所有情況下where的列InterestType他們落入下的WebsitePhone在其他行。

現在,我有以下查詢:

    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

如果這些是數據庫中的行,則理想的查詢將返回:

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

如果您想要帳號:

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)因為不應該有重復項(除非可以為給定帳戶復制興趣類型)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM