代码之家  ›  专栏  ›  技术社区  ›  Steve Wall

其他列相等时检索最新行的SQL查询

sql
  •  1
  • Steve Wall  · 技术社区  · 14 年前

    我很难找出检索特定数据集的SQL语句。如果除上次更新日期外所有列都相等,则我要最新的。例如。

    Book    Author   Update
    John    Foo      1/21/2010
    John    Foo      1/22/2010
    Fred    Foo2     1/21/2010
    Fred    Foo2     1/22/2010
    


    Book    Author   Update
    John    Foo      1/22/2010
    Fred    Foo2     1/22/2010
    

    蒂亚,

    4 回复  |  直到 14 年前
        1
  •  4
  •   Tom H    14 年前
    SELECT
        book,
        author,
        MAX(update)
    FROM
        My_Table
    GROUP BY
        book,
        author
    

    这只适用于这种特殊情况,因为 全部的

    SELECT
        T.book,
        T.author,
        T.update
    FROM
        (SELECT book, MAX(update) AS max_update FROM My_Table GROUP BY book) SQ
    INNER JOIN My_Table T ON
        T.book = SQ.book AND
        T.update = SQ.max_update
    
        2
  •  2
  •   CaffGeek    14 年前

    把它修好了

        DROP TABLE #tmpBooks  
        CREATE TABLE #tmpBooks  
        (
            Book    VARCHAR(100),
            Author  VARCHAR(100),
            Updated DATETIME
        )
    
        INSERT INTO #tmpBooks VALUES ('Foo', 'Bar', '1/1/1980')
        INSERT INTO #tmpBooks VALUES ('Foo', 'Bar', '1/1/1990')
        INSERT INTO #tmpBooks VALUES ('Foo', 'Bar', '1/1/2000')
        INSERT INTO #tmpBooks VALUES ('Foo', 'Bar', '1/1/2010')
        INSERT INTO #tmpBooks VALUES ('Foo2', 'Bar2', '1/1/1980')
        INSERT INTO #tmpBooks VALUES ('Foo2', 'Bar2', '1/1/1990')
        INSERT INTO #tmpBooks VALUES ('Foo2', 'Bar2', '1/1/2000')
    
        SELECT   Book, Author, Max(Updated) as MaxUpdated
           FROM  #tmpBooks
           GROUP BY Book, Author
    

    Book            Author          MaxUpdated
    --------------- --------------- -----------------------
    Foo             Bar             2010-01-01 00:00:00.000
    Foo2            Bar2            2000-01-01 00:00:00.000
    
    (2 row(s) affected)
    
        3
  •  1
  •   harpo    14 年前

    这会得到你想要的,但我知道这不是你想要的。

    SELECT Book, Author, MAX(Update)
      FROM BookUpdates
     GROUP BY Book, Author
    

        4
  •  0
  •   Jan    14 年前

    试试这个(没有数据可以测试,但应该可以):

    SELECT
        bu.Book,
        bu.Author
    FROM
        BookUpdates bu
            JOIN
        (SELECT MAX(Updated) as Date FROM BookUpdates) max
    WHERE
        bu.Updated = max.Date;