COUNT OVER PARTITION SQL Server中的COUNT

时间:2017-12-13 09:15:06

标签: sql sql-server

SELECT MobilePhone, COUNT(MobilePhone) OVER(PARTITION BY MobilePhone) AS CountMobilePhone
FROM ES_TABLE 
WHERE applic IN ( SELECT appl 
                FROM Campaign JOIN Client ON Campaign.ClientID = Client.ClientID 
                WHERE Client.ClientCode = 'OPIS')

那就是我的查询

输出

MobilePhone  | CountMobilePhone
121928       |    1
912819       |    1
129819       |    3
198219       |    5
918298       |    5

我想通过CountMobilePhone进行分组计数。就像这样

Count   | CountMobilePhone
2       |    1
1       |    3
2       |    5

可能吗?我已多次尝试过但收到错误

2 个答案:

答案 0 :(得分:3)

试试这个

WITH CTE
AS
(

SELECT 
    MobilePhone, 
    COUNT(MobilePhone) OVER(PARTITION BY MobilePhone) AS CountMobilePhone
    FROM ES_TABLE 
    WHERE EXISTS  ( SELECT  1
                    FROM Campaign JOIN Client ON Campaign.ClientID = Client.ClientID 
                    WHERE Client.ClientCode = 'OPIS' AND appl = ES_TABLE.applic)

)
SELECT
    [Count] = COUNT(1),
    CountMobilePhone
    FROM CTE
        GROUP BY CountMobilePhone

我还用存在替换IN以获得更好的性能

答案 1 :(得分:3)

只需对计数本身进行另一次聚合:

SELECT CountMobilePhone, COUNT(*) AS cnt
FROM
(
    SELECT COUNT(MobilePhone) OVER(PARTITION BY MobilePhone) AS CountMobilePhone
    FROM ES_TABLE 
    WHERE applic IN (SELECT appl FROM Campaign INNER JOIN Client
                         ON Campaign.ClientID = Client.ClientID 
                     WHERE Client.ClientCode = 'OPIS')
) t
GROUP BY CountMobilePhone
ORDER BY CountMobilePhone;