我希望有人可以提供帮助。我有一张桌子......
name date number
John 2014-01-01 5
Sally 2014-01-01 7
John 2013-12-24 2
Sally 2013-12-24 7
John 2013-11-10 1
Sally 2012-11-10 8
我想获得每个人的最新2(或x)记录,例如
John 2014-01-01 5
John 2013-12-24 2
Sally 2014-01-01 7
Sally 2013-12-24 7
我不知道从哪里开始。如果有人能够对此有所了解,我将非常感激。如果您能够为学习目的解释解决方案,那也很好(如果您有时间的话)!
非常感谢
朱
答案 0 :(得分:2)
SELECT x.*
FROM my_table x
JOIN my_table y
ON y.name = x.name
AND y.date >= x.date
GROUP
BY x.name
, x.date
HAVING COUNT(*) <= 2
ORDER
BY name,date DESC;
答案 1 :(得分:0)
Select Count(Distinct Names) "yourtable"
Group By Names
计数结果你将乘以x和tis将是你下一个查询的限制意义:
Select Distinct Names,date,number from "yourtablename"
limit Count(Distinct Names)*X
order by Names