简体   繁体   中英

How to use group by to get only one row

I have this query:

  SELECT
  Max(l.created) AS created,
  l.unit_id,
  l.activity_id AS Active
  FROM unit_log AS l
  GROUP BY l.unit_id, l.activity_id

What I need and can't seem to get, is the MAX() row per unit_id. I need the unit_id in the query because I am joining to another table. The created column is a timestamp.

Each unit_id will have hundreds of entries. All I'm concerned with is the most recent one per unit. Can someone show me why this isn't working?

SELECT l.unit_id, l.created, l.activity_id
FROM unit_log l
JOIN (SELECT unit_id, MAX(created) AS maxc
      FROM unit_log
      GROUP BY unit_id) m
ON l.unit_id = m.unit_id AND l.created = m.maxc

Your query should work just fine, as long as there is only one activity_id per unit_id. As it's written, it will give you one row per unit per activity id.

Perhaps you need:

SELECT Max(l.created) AS created, l.unit_id FROM unit_log AS l WHERE l.activity_id = 1 --or whatever indicates active GROUP BY l.unit_id, l.activity_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