这是我的表:
somename something somedate
Tom aaa 2013-07-30 15:16:07.710
Tom bbb 2013-07-29 15:16:07.710
Matt ccc 2013-07-28 15:16:07.710
Matt ddd 2013-07-27 15:16:07.710
Matt eee 2013-07-27 15:16:07.713
我想要返回第1行(最近为客户Tom)和第3行(最近为客户Matt)。
更新:我添加了第3列,'某事'
所以结果应该是:
某人 汤姆 亚光某事
aaa
ccc
答案 0 :(得分:4)
SELECT somename ,
MAX(somadate)
FROM attempts
GROUP BY somename
按somename
进行分组,对于任何名为Tom的人,您都会得到1个结果,因此该字段需要唯一。所以,也许在表格中寻找一个独特的字段,可能是UserName
或Email
等等。那么,你最终会得到:
SELECT somename ,
MAX(somadate) ,
UniqueField
FROM attempts
GROUP BY somename ,
UniqueField
答案 1 :(得分:3)
你去吧
select somename, max(somedate) from sometable group by somename
答案 2 :(得分:3)
由于您使用的是SQL Server,因此可以使用row_number()
来获取结果:
select somename, somedate
from
(
select somename, somedate,
row_number() over(partition by somename
order by somedate desc) seq
from yourtable
) d
where seq = 1;
请参阅Demo
答案 3 :(得分:1)
CREATE TABLE SomeTable(
SomeName VARCHAR(5),
SomeDate DATE
)
INSERT INTO SomeTable
VALUES ('Tom','2013-07-01')
, ('Tom','2013-06-30')
, ('Bob','2013-07-01')
, ('Bob','2013-06-30')
, ('Bob','2013-06-29')
SELECT DISTINCT SomeName, MAX(SomeDate)
FROM SomeTable
GROUP BY SomeName