Group by不给我最新的组

时间:2011-10-14 19:59:38

标签: mysql group-by distinct

我试图从我的表中得到明显的结果,人们说我应该使用该组。这样做了一半...我现在得到了明显的结果,但结果不是最新的线程...我的表包含几个建筑物的公寓状态。公寓可以多次找到,因为它是历史表...我需要做一个选择,以检索具有当前状态的不同公寓。

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

我目前正在处理:

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

2 个答案:

答案 0 :(得分:0)

 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

答案 1 :(得分:0)

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)