分组取最大2条记录方法

来源:互联网 发布:app原型设计工具 mac 编辑:程序博客网 时间:2024/06/11 13:26

题目假设是这样:

我的数据库 表A
有下列字段
id 字段
name varchar
type int
createtime varchar 格式'2011-03-05 10:10:25'
type 有 1 2 3 4 5种
现在我想查询的是type为 2 5 3的 各 两条 记录,根据时间降冪排序。

 

解法如下:

select *
from tb A
where type in (2,5,3) and 2>(select count(*) from tb where A.type=type and A.createtime<createtime)
order by type,createtime desc