1

I have three tables

USER :         idUser, Username
USERLOCATION : idUser, idLocation
SESSION :      idUser, idSession

What I want to find is all the users that are from a particular location and count how many sessions they have had. I'm nearly there with this SQL

    SELECT  u.idUser, u.Username, s.idSession
      FROM  rempad.User u
INNER JOIN  rempad.UserLocation l ON u.idUser = l.idUser
INNER JOIN  rempad.Session s ON u.idUser = s.idUser
     WHERE  l.idLocation = 12

This returns all the users belonging to a particular location and all the session ids. Where I am stuck is that I really want to be able able to count the the sessions for each user.

I've tried...

SELECT u.idUser, u.Username, COUNT(s.idSession) as SessionCount

but this returns only a single row and counts all the sessions in the session table rather than counting the sessions that belong to each individual user at that location.

Do I need to do a nested SELECT statement? I'm not really sure how to go about writing the query.

Any help much appreciated.

L

1
  • COUNT(blah) as something Commented Sep 2, 2013 at 18:38

2 Answers 2

1

Try this:-

SELECT  u.idUser, u.Username, count(s.idSession) as x
      FROM  rempad.User u
INNER JOIN  rempad.UserLocation l ON u.idUser = l.idUser
INNER JOIN  rempad.Session s ON u.idUser = s.idUser
     WHERE  l.idLocation = 12
GROUP  BY u.iduser, 
      u.username 
Sign up to request clarification or add additional context in comments.

1 Comment

@LindaKeating:- Try using the Group By clause then. Updated my answer!!
1

I believe it would be better to use Group by along with the above

SELECT u.iduser, 
       u.username, 
       Count(s.idsession) AS x 
FROM   USER u 
       INNER JOIN userlocation l 
               ON u.iduser = l.iduser 
       INNER JOIN session s 
               ON u.iduser = s.iduser 
WHERE  l.idlocation = 12 
GROUP  BY u.iduser, 
          u.username 

3 Comments

sqlfiddle.com/#!2/8a29d/1/0 this is an example, seems to group by user
Thankyou so much - I had made a mistake when using the group by - but tried it again and it worked. REally appreciate your help.
Glad that I could help

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.