简体   繁体   中英

SQL group by get latest results

My question is in the picture:

SQL query

请看图片

From the results you are looking for it seems as though you are trying to get the highest value from Rev when you do the grouping and also if there two or more records with the highest Rev to get the highest num.

You could run something like this

-- Once you have a unique records, select the unique records with largest "Rev"
select
      num
    , week
    , Po_num
    , max(Rev) Rev
from
      (
       -- First get the max "num" for a unique set of week, Po_num and Rev records
       select
             max(num) num
           , week
           , Po_num
           , Rev
       from
             table
       group by
             week
           , Po_num
           , Rev
      )
;  

if you need the last rev by num and week for each po_num you should use a subquery for max ver

    select * 
    from  table a
    inner join  (

      select    max(rev) max_rev
               , week
               , Po_num
           from  table
           group by week, Po_num
    ) t on t.max_rev  = a.rev 
            and t.po_num  = a.po_num  
            and t.week  = a.week 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM