简体   繁体   中英

Group By and Count in a single sql query

I have two tables - users and login_reports.

users table have 4 columns - id, email, name, password, created_at, updated_at login_reports table have 3 columns - id, user_id, created_at.

Every time user logins, an entry is created in login_reports.

Now I have to write a query to show login reports on admin dashoard. The query should return rows of users having login count and last login. Can someone help me with this.

SELECT users.id AS id, count(users.id) FROM users
INNER JOIN login_reports
ON users.id = login_reports.user_id
GROUP BY users.id

How do I get last login timestamp ie the last entry of that user in login_reports (created_at).

I think you want something like this

select u.id, count(r.id), max(r.created_at) 
from user u 
left join login_reports r on r.user_id = u.id
group by u.id

edit: thanks @tcadidot0

I used following query to solve this

SELECT users.id as id, count(login_reports.id) as login_count, login_reports.created_at as last_login FROM users LEFT JOIN (SELECT * FROM login_reports ORDER BY created_at DESC) login_reports ON users.id = login_reports.user_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM