创建 SQL 查询以检索最新记录
我正在为我的项目团队创建一个状态板模块。 状态板允许用户将其状态设置为“进”或“出”,并且还可以提供注释。 我计划将所有信息存储在一个表中......数据示例如下:
Date User Status Notes
-------------------------------------------------------
1/8/2009 12:00pm B.Sisko In Out to lunch
1/8/2009 8:00am B.Sisko In
1/7/2009 5:00pm B.Sisko In
1/7/2009 8:00am B.Sisko In
1/7/2009 8:00am K.Janeway In
1/5/2009 8:00am K.Janeway In
1/1/2009 8:00am J.Picard Out Vacation
我想查询数据并返回每个用户的最新状态,在这种情况下,我的查询将返回以下结果:
Date User Status Notes
-------------------------------------------------------
1/8/2009 12:00pm B.Sisko In Out to lunch
1/7/2009 8:00am K.Janeway In
1/1/2009 8:00am J.Picard Out Vacation
我正在尝试找出 TRANSACT-SQL 来实现这一点? 任何帮助,将不胜感激。
I am creating a status board module for my project team. The status board allows the user to to set their status as in or out and they can also provide a note. I was planning on storing all the information in a single table ... and example of the data follows:
Date User Status Notes
-------------------------------------------------------
1/8/2009 12:00pm B.Sisko In Out to lunch
1/8/2009 8:00am B.Sisko In
1/7/2009 5:00pm B.Sisko In
1/7/2009 8:00am B.Sisko In
1/7/2009 8:00am K.Janeway In
1/5/2009 8:00am K.Janeway In
1/1/2009 8:00am J.Picard Out Vacation
I would like to query the data and return the most recent status for each user, in this case, my query would return the following results:
Date User Status Notes
-------------------------------------------------------
1/8/2009 12:00pm B.Sisko In Out to lunch
1/7/2009 8:00am K.Janeway In
1/1/2009 8:00am J.Picard Out Vacation
I am try to figure out the TRANSACT-SQL to make this happen? Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
聚合在
子查询派生表中,然后连接到它。Aggregate in a
subqueryderived table and then join to it.则只会扫描表一次而不是两次
另一种方式,如果您仅使用子查询 sql server 2005 及更高版本,
another way, this will scan the table only once instead of twice if you use a subquery
only sql server 2005 and up
派生表可以工作,但如果这是 SQL 2005,则 CTE 和 ROW_NUMBER 可能会更清晰:
这也有助于显示每个用户的最新 x 状态。
The derived table would work, but if this is SQL 2005, a CTE and ROW_NUMBER might be cleaner:
This would also facilitate the display of the most recent x statuses from each user.
另一种简单的方法:
Another easy way:
为每条记录添加一个自增主键,例如UserStatusId。
那么您的查询可能如下所示:
日期用户状态注释
Add an auto incrementing Primary Key to each record, for example, UserStatusId.
Then your query could look like this:
Date User Status Notes