【问题标题】:SELECT ONE Row with the MAX() value on a column在列上选择具有 MAX() 值的行
【发布时间】:2012-12-06 20:32:43
【问题描述】:

我有一个非常简单的每月通讯数据集:

id  | Name          | PublishDate   | IsActive
1   |  Newsletter 1 | 10/15/2012    |     1
2   |  Newsletter 2 | 11/06/2012    |     1  
3   |  Newsletter 3 | 12/15/2012    |     0
4   |  Newsletter 4 | 1/19/2012     |     0

等等。

PublishDate 是唯一的。

结果(基于以上):

id  | Name          | PublishDate   | IsActive
2   |  Newsletter 2 | 11/06/2012    |     1  

我想要的很简单。我只想要 IsActive 和 PublishDate = MAX(PublishDate) 的 1 个时事通讯。

【问题讨论】:

  • 其他类似的问题似乎都在处理数据分区并在这些分区上聚合最大值。如果有人发现这确实是重复的,请标记为这样。
  • 老兄,请解释你的反对意见。
  • 那么根据样品,你想退回哪一个?
  • 你使用的是哪个数据库?
  • @Bohemian tsql 暗示 mssql

标签: sql sql-server tsql


【解决方案1】:
select top 1 * from newsletters where IsActive = 1 order by PublishDate desc

【讨论】:

    【解决方案2】:

    你可以使用row_number():

    select id, name, publishdate, isactive
    from
    (
      select id, name, publishdate, isactive,
        row_number() over(order by publishdate desc) rn
      from table1
      where isactive = 1
    ) src
    where rn = 1
    

    SQL Fiddle with Demo

    您甚至可以使用选择max() 日期的子查询:

    select t1.*
    from table1 t1
    inner join
    (
      select max(publishdate) pubdate
      from table1
      where isactive = 1
    ) t2
      on t1.publishdate = t2.pubdate
    

    SQL Fiddle with Demo

    【讨论】:

      【解决方案3】:
      CREATE TABLE Tmax(Id INT,NAME VARCHAR(15),PublishedDate DATETIME,IsActive BIT)
      INSERT INTO Tmax(Id,Name,PublishedDate,IsActive)
      VALUES(1,'Newsletter 1','10/15/2012',1),(2,'Newsletter 2','11/06/2012',1),(3,'Newsletter 3','12/15/2012',0),(4,'Newsletter 4','1/19/2012',0)
      
      SELECT * FROM Tmax
      
      SELECT t.Id
              ,t.NAME
              ,t.PublishedDate
              ,t.IsActive
      FROM Tmax AS t
          WHERE PublishedDate=
          (
              SELECT TOP 1 MAX(PublishedDate)
              FROM Tmax
              WHERE IsActive=1
          )
      

      【讨论】:

        猜你喜欢
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        • 2012-01-13
        • 2017-11-15
        相关资源
        最近更新 更多