4

我有一个表,其中包含 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

它并没有真正做我想做的事情,我认为真正的解决方案会比这更复杂一些,因为我也需要以某种方式根据今天的日期进行选择。

4

4 回答 4

9
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;
于 2013-07-17T09:07:50.727 回答
1

像这样简单的事情对你有用吗?

SELECT DISTINCT ID, CreatedBy, SeminarDate
FROM CUSTOMERDB.dbo.Seminars
ORDER BY SeminarDate DESC
于 2013-07-17T09:09:20.953 回答
0

select * from 研讨会 order by datediff(SemindarDate,getDate) desc

于 2013-07-17T09:14:28.440 回答
0

以下查询可能会有所帮助。唯一的问题是当您为给定所有者举办两个具有相同日期的研讨会时。在这种情况下,查询将返回所有者在该日期的所有研讨会。

;WITH T AS
  (
    SELECT MAX(Date) AS Date, Owner
      FROM Seminars
      GROUP BY Owner
  )
SELECT S.*
  FROM T
  INNER JOIN Seminars S ON T.Owner=S.Owner AND T.Date=S.Date
  ORDER BY S.Date
于 2013-07-17T09:41:40.010 回答