繁体   English   中英

从 group by 中获取最少的行

[英]Get least row from group by

我有一张表,我想通过 _Uid 和 _status 获取组上的最小时间戳。

select _id, _Uid, max(_status) as _status, min(_timestamp) as _last_updated_ 
from table_name 
where 
group by _Uid, _status

输出

_id     _Uid    _status _timestamp
17685   14635   21  2019-07-20 10:05:50
17167   14635   16  2019-07-16 07:42:54
17687   14635   12  2019-07-20 10:07:02
17020   14635   8   2019-07-15 08:46:08
17705   14640   13  2019-07-20 11:35:39
17706   14640   9   2019-07-20 11:36:15
17019   14640   8   2019-07-15 08:46:08

首选输出

_id     _Uid    _status _timestamp
17685   14635   21  2019-07-20 10:05:50
17705   14640   13  2019-07-20 11:35:39

这是我在 join 中使用的查询之一。

您应该尝试使用子查询:

SELECT m._id,m._Uid,m._status, min(m._timestamp) AS _timestamt
  FROM(SELECT _id,_Uid,max(_status) as _status
         FROM mytable
         GROUP BY _Uid
      ) x
  JOIN mytable m ON m._id = x._id
    AND m._Uid = x._Uid
    AND m._status = x._status
  GROUP BY m._id,m._Uid,m._status

这个想法是首先使用 group by 来评估状态,然后使用第二个 group by 来获取时间戳。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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