简体   繁体   English

SQL Group按日期只选择1条记录

[英]SQL Group by date only choose 1 record

I am trying to return only one record for the following table but not working. 我试图只返回下表中的一条记录,但没有工作。 It return multiple record.Please advise, thank you 它返回多个记录。请指教,谢谢

I suspect with the problem with groupby 我怀疑groupby的问题

CreateDate              Firstname EventID 
2013-05-13 18:11:35.187 Jack    0CD7B08A-0EAF-4515-9DE1-00FC6DB29A61
2013-05-13 18:11:35.310 Paul    16A584D5-E9B7-4617-8DC9-089C628E0ED5
2013-05-13 20:14:33.863 Craig   AAA21035-1377-443D-9BEE-0C0761534803

Here is the sql query for the result above: 这是上面结果的sql查询:

 SELECT MAX (CreateDate) AS Create_Date, Firstname ,EventID
    FROM SessionsEvents
    WHERE TRN='0391588'

GROUP BY Firstname , TRN, EventID

Its Group data by FirstName after that with TRN and after that with EventID that TRN persent in your query and should be same in all resultset and FirstName, EventID columns have not same data for grouping and rows are separate in resultset then if you need maximum create date you should use TOP keyword for SQL Server: 它之后使用FirstName通过FirstName对数据进行分组,之后使用EventID使查询中存在TRN并且在所有结果集和FirstName,EventID列中相同,对于分组没有相同的数据,并且在结果集中行是分开的,那么如果您需要最大值创建日期您应该使用SQL Server的TOP关键字:

SELECT TOP 1 MAX (CreateDate) AS Create_Date, Firstname ,EventID
FROM SessionsEvents
WHERE TRN='0391588'
GROUP BY Firstname , TRN, EventID

You don't want GROUP BY. 你不想要GROUP BY。 You want TOP 1 with ORDER BY instead to get only the latest record by CreateDate. 您想要使用ORDER BY的 TOP 1来获得CreateDate的最新记录。

SELECT TOP 1 CreateDate, Firstname ,EventID
FROM SessionsEvents
WHERE TRN='0391588'
ORDER BY CreateDate DESC

如果您对同一TRN有不同的FirstNameEventID ,您将获得多个组。

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

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