trante
trante

Reputation: 34006

MySQL for grouping with one column and getting a subgroup from another column

I have a MySQL Table. I put the schema to this fiddle.
In my table when a user logs in I record him/her to mytable. In one day same user can log in several times. So I need to know how many times a user logged in each day.

I need an output like this:

I tried this:

SELECT COUNT(*) AS "times", username, date
FROM mytable GROUP BY date ORDER BY date DESC

But it gave me this:
- 2013-01-30 - Michael - 6 times
- 2013-01-29 - John- 4 times
- 2013-01-28 - Michael - 6 times

Can you recommend a query for this?

Upvotes: 3

Views: 5387

Answers (3)

sgeddes
sgeddes

Reputation: 62841

Just add username to your GROUP BY clause.

SELECT COUNT(*) AS "times", username, date
FROM mytable 
GROUP BY date, username ORDER BY date DESC

http://sqlfiddle.com/#!2/b5701/11

Upvotes: 7

srini.venigalla
srini.venigalla

Reputation: 5145

SELECT date, username, COUNT(1) AS "times" FROM mytable GROUP BY date, username ORDER BY date DESC

Upvotes: 2

echo_Me
echo_Me

Reputation: 37233

you should Group by username also.

try this

   SELECT COUNT(*) AS times, username, date
  FROM mytable group by date,username ORDER BY date DESC

SQL FIDDLE DEMO

Upvotes: 1

Related Questions