Patrioticcow
Patrioticcow

Reputation: 27038

mysql, php, how to get a count of users?

i have a table like this:

user  | session
test1 | 11
test1 | 11
test1 | 11
test1 | 21
test1 | 21
test2 | 2
test2 | 2
test3 | 3
test3 | 3
test3 | 32
test3 | 32

i would like to get back that user 1 has 2 sessions, user 2 has 1 sessions, user 3 has 2 sessions bassically how many the same sessions a user has?

i've tryed $sql4 = SELECT user, session , count(*) FROMtablegroup by user, session

and i get the distinct sessions but not the count

any ideas? thanks

edit:

if i use SELECT user, count(*) FROM users GROUP BY user i get test 1 = 5. it give's me the total nr or sessions instead of total nr of sessions that are the same. in this case 2

Upvotes: 0

Views: 193

Answers (2)

Patrick Desjardins
Patrick Desjardins

Reputation: 140803

If you want to know the overall number of person online you just need to count the number of user regardless of the session

$sql4 = SELECT COUNT(*) from (
        SELECT  distinct(user)
        FROM table) as innerquery

This will group all by user what ever the session. The result will be a simple integer.

If you need to count the amount of session of each user and do not want to have a count for each session you need to remove the duplicate with a Distinct keyword.

$sql4 = SELECT user, count(distinct(session)) 
        FROM table 
        GROUP by user

The result will be a list of user-># of session

Upvotes: 1

RiaD
RiaD

Reputation: 47620

SELECT user, count(DISTINCT session) FROM users GROUP BY user

DISTINCT used to calc only unique sessions

Upvotes: 3

Related Questions