This is my query:
Select COUNT(*)
From
Users u
Inner Join
UsersLoginHistory uh On u.UserID = uh.UserID
Where
1 = 1
And
u.AccountID = 37
Group By u.UserID
What I’d like to be able to get is Count(*) should be returning a number after grouping on u.UserId. But it returns the Count(*) before the group by is made.
So I can rewrite the above query as:
Select COUNT(*)
From (
Select u.Username
From
Users u
Inner Join
UsersLoginHistory uh On u.UserID = uh.UserID
Where
1 = 1
And
u.AccountID = 37
Group By u.UserID
) v
But I need to find out why is the Count(*) returning records before a group by is made and how can I fix the 1st query itself.
EDIT: Sample Records
Users table
UserId Username
102 tom.kaufmann
UserLoginHistory table
UsersLoginHistoryID UserID LoginDateTime LogoutDateTime IPAddress
1 102 2012-09-28 01:16:00 NULL 115.118.71.248
2 102 2012-09-28 01:29:00 2012-09-28 01:29:00 127.0.0.1
3 102 2012-09-28 01:32:00 2012-09-28 01:32:00 127.0.0.1
4 102 2012-09-28 01:41:00 NULL 115.118.71.248
5 102 2012-09-28 01:43:00 2012-09-28 07:04:00 115.118.71.248
and so on..
Haven’t writted every single record in this DB.
Based on your second query which you say returns the desired results (and assuming
UserIDis the PK ofUsers) I presume this is what you needThis will be more efficient than expanding out all the joined rows then collapsing them again with
Group By u.UserIDand counting the number of rows that result.