如何根据多个字段选择不同的行

时间:2013-07-17 09:04:13

标签: sql sql-server select distinct

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

答案 0 :(得分:7)

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;

答案 1 :(得分:1)

为你做一些简单的工作吗?

SELECT DISTINCT ID, CreatedBy, SeminarDate
FROM CUSTOMERDB.dbo.Seminars
ORDER BY SeminarDate DESC

答案 2 :(得分:0)

  

通过datediff(SemindarDate,getDate)desc从研讨会中选择*

答案 3 :(得分: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