How to get all the fields of a row using the SQL MAX function?

后端 未结 3 1301
梦毁少年i
梦毁少年i 2020-12-15 13:21

Consider this table (from http://www.tizag.com/mysqlTutorial/mysqlmax.php):

Id     name               type     price 
123451 Park\'s Great Hits  Music    19.         


        
相关标签:
3条回答
  • 2020-12-15 13:27

    This is the greatest-n-per-group problem that comes up frequently. My usual way of solving it is logically equivalent to the answer given by @Martin Smith, but does not use a subquery:

    SELECT T1.Id, T1.name, T1.type, T1.price 
    FROM Table T1
    LEFT OUTER JOIN Table T2
      ON (T1.type = T2.type AND T1.price < T2.price)
    WHERE T2.price IS NULL;
    

    My solution and all others given on this thread so far have a chance of producing multiple rows per value of type, if more than one product shares the same type and both have an equal price that is the max. There are ways to resolve this and break the tie, but you need to tell us which product "wins" in case like that.

    You need some other attribute that is guaranteed to be unique over all rows, at least for rows with the same type. For example, if the product with the greater Id value should win, you can resolve the tie this way:

    SELECT T1.Id, T1.name, T1.type, T1.price 
    FROM Table T1
    LEFT OUTER JOIN Table T2
      ON (T1.type = T2.type AND (T1.price < T2.price
           OR T1.price = T2.price AND T1.Id < T2.Id))
    WHERE T2.price IS NULL;
    
    0 讨论(0)
  • 2020-12-15 13:36

    Edit Just updating mine to meet the clarified requirement

    SELECT Id, name, type,price 
    FROM Table T1
    WHERE NOT EXISTS(
              SELECT * FROM TABLE T2 
              WHERE T1.type=t2.type 
              AND T2.Price >= T1.Price 
              AND T2.Id > T1.Id
              )
    
    0 讨论(0)
  • 2020-12-15 13:51

    You can do it with a subselect

    SELECT id, name, type, price FROM products p1
    WHERE EXISTS (Select type, max(price) FROM Products p2 
                  GROUP BY type
                  WHERE p1.type=p2.type AND p1.price=p2.MAX(price))
    

    or an inner join

    SELECT id, name, type, price FROM products p1
    INNER JOIN (Select type, max(price) FROM Products p2 GROUP BY type) maxPrice
             ON maxPrice=price=p1.price AND maxPrice.type=p1.price
    
    0 讨论(0)
提交回复
热议问题