简体   繁体   中英

Get Count() for DISTINCT values for each field SQL Server

I have a phonenumber field like:

**phonenumbers**
0729643482
0723412678
0734231567
0745297334
0729643482
0720606706
0729643482
0720606706

There are thousands of entries. I wanted to get top 10 phonenumbers with greatest count. this can be displayed as

**phonenumber     count**
0729643482      3
0720606706      2
.
.
.
(entry 10)      1

From some of the few related questions i understand i can use rank() then group by but i have never done this before. Here is what i have:

select phonenumber,cnt FROM 
(select phonenumber, cnt, rank() over (partition by phonenumber order by cnt desc) rnk
from (select distinct phonenumber, count(phonenumber) cnt
            from ozekiout
            group by phonenumber
            order by phonenumber, count(phonenumber) desc) 
)
where rnk = 1;

You don't need the rank function, you can use a normal count with TOP 10 :

SELECT  TOP 10 phonenumber, [count] = COUNT(*)
FROM    ozekiout
GROUP BY Phonenumber
ORDER BY [count] DESC;

If you want to include more than 10 results if there are ties eg

Phonenumber  count
01111111111   18
01111111112   15
01111111113   15
01111111114   14
01111111115   13
01111111116   13
01111111117   12
01111111118   12
01111111119   10
01111111120   10
01111111121   10
01111111122   10

.... CUT OFF

01111111122   9

you can use:

SELECT  TOP 10 WITH TIES phonenumber, [count] = COUNT(*)
FROM    ozekiout
GROUP BY Phonenumber
ORDER BY [count] DESC;

尝试这个 :

select phonenumber,Count(*) as count from ozekiout group by phonenumber order by count desc limit 10;

SELECT TOP 10 phonenumber, [count] = COUNT(*) FROM ozekiout GROUP BY Phonenumber ORDER BY [count] DESC;

Works ryt....thank you guys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM