[英]How to get Max date from my query in SQL Server?
How can I get Max date (latest date) from my query for each player? 如何从查询中获取每个玩家的最大日期(最新日期)?
Data from table: 表中的数据:
Id PlayerId Username DateCreated
2 777 player1 2018-01-01 00:00:00.0000000
3 778 player2 2018-05-05 00:00:00.0000000
5 777 player1 2018-04-04 00:00:00.0000000
So the result will be just one record for player1(max DateCreated) and one record for player2 因此,结果将仅是player1(最大DateCreated)的一条记录和player2的一条记录
IF (@pageNumber IS NOT NULL AND @pageSize IS NOT NULL)
BEGIN
SET @minNumber = (@pageNumber - 1) * @pageSize;
SET @maxNumber = @pageNumber * @pageSize;
SET @sql = @sql + ' TOP(@maxNumber) ROW_NUMBER () OVER (ORDER BY ' + @orderBy +') AS [RowNumber], ';
END
ELSE
SET @sql = @sql + ' ROW_NUMBER () OVER (ORDER BY ' + @orderBy + ') AS [RowNumber], ';
SET @sql = @sql + ' COUNT(*) OVER () AS [RecordCount],* FROM (SELECT [PlayerId], [Username], [DateCreated], [Response] FROM TABLE with (nolock) ';
You can replace the subquery by below one. 您可以将子查询替换为下面的子查询。
SELECT [PlayerId], MAX([DateCreated]) AS LastDate FROM TABLE with (nolock)
group by [PlayerId]
What you want is this: 您想要的是:
SELECT Id
,PlayerId
,Username
,DateCreated
FROM
(
SELECT Id
,PlayerId
,Username
,DateCreated
,ROW_NUMBER() OVER (Partition By PlayerId Order By DateCreated DESC) AS FilterMostRecent
FROM Players
) x
WHERE FilterMostRecent = 1
I suggest you use SQLFiddle to help us helping you :) 我建议您使用SQLFiddle帮助我们帮助您:)
Try the query and see if it is what you expect 尝试查询,看看是否是您期望的
http://sqlfiddle.com/#!18/af1ec/4/0 http://sqlfiddle.com/#!18/af1ec/4/0
And please, only use dynamic SQL as a last resort 而且请只使用动态SQL作为最后的手段
http://www.sommarskog.se/dynamic_sql.html http://www.sommarskog.se/dynamic_sql.html
and really, really avoid (NOLOCK) 真的,真的要避免(NOLOCK)
https://blogs.sentryone.com/aaronbertrand/bad-habits-nolock-everywhere/ https://blogs.sentryone.com/aaronbertrand/bad-habits-nolock-everywhere/
unless you really know what you are doing. 除非您真的知道自己在做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.