Group by doesn't give me the newest group

ⅰ亾dé卋堺 提交于 2019-12-13 04:03:10

问题


I was trying to get the distinct result from my table, and people said I should use the group by. This worked half way... I now get the distinct result but the result is not the newest thread... my table contains status on apartments from several buildings. The apartments can be found many times since it's a history table... I need to make a select that retrieves the distinct apartments with the current status.

ID    Building Apartment_id  Status
1     1        1             1
2     1        1             2
3     2        2             3
4     2        4             2
5     2        3             2
6     2        5             1
7     2        6             1

I'm currently working with:

SELECT * FROM `ib30_history` GROUP BY apartment_id, building ORDER BY id DESC

回答1:


SELECT 
  Building
  , Appartment_id
  , Status 
FROM ib30_history a
WHERE id = ( SELECT MAX(id) FROM ib30_history b 
             WHERE b.Building = a.Building AND b.Appartment_id = a.Appartment_id)



回答2:


 select h.apartment_id, h.status
  from history h 
       join (select apartment_id, max(status) status
               from history
              group by apartment_id) recent 
       on h.apartment_id = recent.apartment_id 
      and h.status = recent.status


来源:https://stackoverflow.com/questions/7772913/group-by-doesnt-give-me-the-newest-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!