Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT in COUNT OVER PARTITION SQL Server

Tags:

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')

thats my query

the output is

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

I want to group by CountMobilePhone for counting. to be like this

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

is that possible? I've tried several times but getting error

like image 438
TARA Avatar asked Dec 13 '17 09:12

TARA


People also ask

Can you do a COUNT over partition in SQL?

SQL Count with Partition By clause is one of the new powerful syntax that t-sql developers can easily use. For example, while selecting a list of rows you can also calculate count of rows sharing the same field values without using subselects or SQL CTE (Common Table Expressions) in your query.

Can you use distinct in partition by?

Count Distinct is not supported by window partitioning, we need to find a different way to achieve the same result.

How does COUNT (*) Work SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.

What is over partition by in SQL Server?

The SQL PARTITION BY expression is a subclause of the OVER clause, which is used in almost all invocations of window functions like AVG() , MAX() , and RANK() . As many readers probably know, window functions operate on window frames which are sets of rows that can be different for each record in the query result.


1 Answers

Just do another aggregation on the counts themselves:

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;
like image 194
Tim Biegeleisen Avatar answered Sep 29 '22 11:09

Tim Biegeleisen