SQL服务器 - 如何选择每用户最近的记录? [英] SQL Server - How to select the most recent record per user?

查看:122
本文介绍了SQL服务器 - 如何选择每用户最近的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个SQL命令应该是进入了数据库中的最后一行上绘制。

基本上,当用户(在这个论坛等)提交最后一个线程,它的用户能够与他的螺纹标题,螺纹段和数据的页面重定向,如用户名和时间该线程已提交。

我一开始就声明的工作:

  SELECT @UserID,u.UsersName,t.ThreadTitle,t.ThreadParagraph
来自用户的为u
INNER JOIN主题为t ON u.UserID = t.UserID
凡@UserID = t.UserId

这是我的问题是,我需要添加一些语句或聚合函数返回我是在线程表中输入的最后一行。我该怎么做呢?我需要什么补充?


解决方案

在MS SQL,您可以使用 TOP 1 对于这一点,还需要由您创建的日期订购时间列下降。

  SELECT TOP 1 @UserID,u.UsersName,t.ThreadTitle,t.ThreadParagraph
来自用户的为u
    INNER JOIN主题为t ON u.UserID = t.UserID
其中,@用户名= t.UserId
ORDER BY [YourDateTimeFiled] DESC

I am trying to execute a SQL command which should draw on the last row that entered the database.

Basically, when a user submits the last thread (like in this forum), it redirects the user to a page with his thread title, thread paragraph and data such as a user name and time the thread was submitted.

I started working on the statement:

SELECT @UserID, u.UsersName, t.ThreadTitle, t.ThreadParagraph
FROM Users as u
INNER JOIN Threads as t ON u.UserID = t.UserID
Where @UserID = t.UserId

The problem that I have is that i need to add some statement or aggregate function to return me the last row that was entered in the threads table. How do I do this? what do I need to add?

解决方案

In MS SQL you can use TOP 1 for this, you also need to order by your created date time column descending.

SELECT TOP 1 @UserID, u.UsersName, t.ThreadTitle, t.ThreadParagraph
FROM Users as u
    INNER JOIN Threads as t ON u.UserID = t.UserID
Where @UserID=t.UserId
ORDER BY [YourDateTimeFiled] DESC

这篇关于SQL服务器 - 如何选择每用户最近的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆