1

I have a table with non-unique column auth_id. I need to select the auth_id value with maximum number of entries.

SELECT auth_id, cnt
FROM (SELECT auth_id, COUNT(auth_id) AS cnt 
FROM articles_authors 
GROUP BY auth_id) articles_num
WHERE cnt = (SELECT MAX(articles_num.cnt))

Here's the data example:

auth_id    article_id
1              2
1              1
1              3
2              2
3              1
3              2

And the output:

auth_id    cnt
1           3

But SQL doesn't see the alias table articles_num. How do I make this WHERE clause with this alias?

ihjn
  • 45
  • 5

4 Answers4

2

Using a limit clause would be much simpler - you simply order a query according to some field, and then just take the first row:

SELECT   auth_id, COUNT(auth_id) AS cnt 
FROM     articles_authors 
GROUP BY auth_id
ORDER BY 2 DESC
LIMIT    1
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Order your data in descending order in your inner query then just take the first one:

SELECT auth_id, cnt
FROM (
    SELECT auth_id, COUNT(auth_id) AS cnt 
    FROM articles_authors 
    GROUP BY auth_id 
    ORDER BY cnt DESC
     )
LIMIT 1
StephaneM
  • 4,779
  • 1
  • 16
  • 33
1

If I understand correctly, you actually want to get one row of the max of the count:

SELECT auth_id, count(auth_id) as cnt
FROM articles_authors
GROUP BY 1
ORDER BY 2 DESC
LIMIT 1

If more than one auth_id have same max count, we need to update this SQL

SIDU
  • 2,258
  • 1
  • 12
  • 23
0

Try this.......

select auth_id, count(auth_id) as cnt 
from articles_authors 
group by auth_id 
order by cnt DESC 
limit 1;

Let me know if it resolves your issue

Rohit Gaikwad
  • 817
  • 2
  • 8
  • 24