SQL Selecting multiple columns based on max value in one column

后端 未结 6 1668
天涯浪人
天涯浪人 2021-02-07 12:22

OK so I have looked theough the other solutions an no help. So here is what I am trying to do. I need to select the row with multiple columns where the value in one column is th

相关标签:
6条回答
  • 2021-02-07 12:47

    You need to find your MAX values in a subquery, then use those results to join to your main table to retrieve the columns.

    SELECT t.OrderFileId, t.ItemNumber, t.ItemCost, t.Warehouse
        FROM YourTable t
            INNER JOIN (SELECT ItemNumber, MAX(OrderFileId) AS MaxOrderId
                            FROM YourTable
                            GROUP BY ItemNumber) q
                ON t.ItemNumber = q.ItemNumber
                    AND t.OrderFileId = q.MaxOrderId
    
    0 讨论(0)
  • 2021-02-07 12:47
    select 
        t.* 
    from 
        table t 
        inner join (
            select itemnumber, max(orderfileid) maxof
            from table
            group by itemnumber
        ) m on t.itemnumber = m.itemnumber 
                and t.orderfileid = m.maxof
    
    0 讨论(0)
  • 2021-02-07 12:51

    I think what you are looking for is the "Having" clause. Take a look at this.

    select orderfileid, max(itemnumber), itemcost, warehouse from MyTable group by orderfileid having max(itemnumber) ;

    0 讨论(0)
  • 2021-02-07 12:57

    Try

    SELECT * FROM `TABLE` WHERE orderfileid=(select max(orderfileid) from TABLE)
    
    0 讨论(0)
  • 2021-02-07 12:57

    you can refer to a similar problem on how to group things using partitioning and picking one per partition in mysql

    Deleting Rows: No Single Member Has More Than x Records

    this is something similar to doing rank over in Oracle. my previous post was for oracle. my bad..

    0 讨论(0)
  • 2021-02-07 13:09

    I wouldn't even use Max. Just combine GROUP BY and ORDER BY

    SELECT * FROM orders GROUP BY item_number ORDER BY orderfileid DESC
    

    then for minimum just change to ASC

    0 讨论(0)
提交回复
热议问题