我有一个表,其中包含有关MSSQL数据库中一系列事件的数据:
ID Name Date Location Owner --- --------------------------------------------------------- ----------- -------------------------------- ----------- 1 Seminar Name 1 2013-08-08 A Location Name 16 2 Another Event Name 2013-07-30 Another Location 18 3 Event Title 2013-08-21 Head Office 94 4 Another Title 2013-08-30 London Office 18 5 Seminar Name 2 2013-08-27 Town Hall 19 6 Title 2013-08-20 Somewhere Else 196 7 Fake Seminar For Testing 2013-08-25 Fake Location 196
希望您可以看到该表包含许多事件,这些事件由我们的应用程序中的多个用户拥有。我试图找出是否存在可以用于为每个用户选择最近发生的事件的查询。我认为显示我想要的最简单方法是显示我正在寻找的理想结果表(基于今天的日期):
ID Name Date Location Owner --- --------------------------------------------------------- ----------- -------------------------------- ----------- 1 Seminar Name 1 2013-08-08 A Location Name 16 2 Another Event Name 2013-07-30 Another Location 18 3 Event Title 2013-08-21 Head Office 94 5 Seminar Name 2 2013-08-27 Town Hall 19 6 Title 2013-08-20 Somewhere Else 196
目前,我能想到的最好的方法是以下查询:
SELECT DISTINCT Owner, Date, ID FROM Seminars GROUP BY Owner, Date, ID ORDER BY Date
它并没有真正做我想做的事,我认为真正的解决方案将比这要复杂一些,因为我也需要根据今天的日期进行选择。
WITH CTE AS ( SELECT *, ROW_NUMBER() OVER(PARTITION BY Owner ORDER BY Date DESC) AS RN FROM tablename ) SELECT ID, Name, Date, Location, Owner FROM CTE WHERE RN = 1;