我有一个包含以下字段的表格:
id
name
date_created
department
我希望按date_created
但我希望每个部门只有2个结果。
我该怎么做?
答案 0 :(得分:2)
这样的事情应该有用 - 你需要得到你的行号,按部门分组:
SELECT Id,
Name,
Date_Created,
Department
FROM (
SELECT @curRow:=CASE WHEN @prevRow = Department THEN @curRow+1 ELSE 1 END AS rn,
Id,
Name,
Date_Created,
Department,
@prevRow:=Department clset
FROM YourTable
JOIN (SELECT @curRow:= 0) r
ORDER BY Department, Date_Created DESC
) t
WHERE rn <= 2
还有一些示例Fiddle。
答案 1 :(得分:-1)
select * from tablename
group by department
order by date_created
limit 0, 2