5

Ok, I have a single MySQL table with the name 'test' and 3 columns.

 ID | playername | lastloginip  
-----------------------------
 1  | user 1     |     1  
 2  | user 2     |     2  
 3  | user 3     |     3  
 4  | user 4     |     4  
 5  | user 5     |     5  
 6  | user 6     |     1  
 7  | user 7     |     1  
 8  | user 8     |     2  

Now, I would like to select ALL the rows where the lastloginip is found multiple times in the table, and then give the count of those rows.

In this case, it should return the number 5 as user 1, 2, 6, 7 and 8 have a lastloginip that is found multiple times.

I already tried using

SELECT COUNT(*) 
FROM (
    SELECT * 
    FROM test 
    GROUP BY lastloginip 
    HAVING COUNT(*) > 1
)  t

But that gave back the number 2 instead of 5.
I am not sure how to set up this query correctly. Most of my findings on the internet keep showing only 2 rows or giving the number 2 instead of 5.

3 Answers 3

11

First COUNT(), then SUM():

SELECT SUM(occurences) 
FROM 
(
   SELECT COUNT(*) AS occurences
   FROM test
   GROUP BY lastloginip
   HAVING COUNT(*)>1
) t
2
  • Thanks i think i have it now. I changed your first 'misunderstood' version of your query to something that works. SELECT SUM(occurrences) FROM( SELECT COUNT(ID) AS occurrences FROM test GROUP BY lastloginip HAVING COUNT(ID)>1) t
    – Snowy007
    Jan 4, 2012 at 0:24
  • I have a feeling I might have done something silly. Hopefully someone else can have a look at my answer and correct it if needed.
    – marnir
    Jan 4, 2012 at 0:27
0

Try this query.

SELECT SUM(loginip) 
FROM(
    SELECT 
    lastloginip, 
    COUNT(lastloginip) 
    as loginip 
    FROM test 
    GROUP BY lastloginip 
    HAVING COUNT(ID)>1
)t
0

You can fetch the sum of occurrences using the above code and if you want to view the records with multiple occurences, refer to the query below-

Select * from test where lastloginip in ( select * from (select lastloginip from test group by lastloginip having count(lastloginip)>1 ) as a)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.