-1

I failed to write SQL code to retrieve maximum number in order_number column. notice that visit_number is group contain more than one record and i want the maximum value of order_number column.

visit_number , Order_number , NAME
111          ,     1        , 001
111          ,     2        , 001
111          ,     3        , 001
222          ,     1        , 252
222          ,     2        , 252 
003          ,     1        , 121
003          ,     2        , 121

I want the result to be like below matrix:

111          ,     3        , 001
222          ,     2        , 252 
003          ,     2        , 121

this is my query

SELECT VISIT_NUMBER , MAX(ORDER_NUMBER) , NAME
from table
group by ( visit_number , name ) 
Matt
  • 14,906
  • 27
  • 99
  • 149
Nawaf
  • 540
  • 1
  • 5
  • 14

3 Answers3

0

Use GROUP BY and the MAX function.

SELECT visit_number, MAX(Order_number), NAME
FROM yourtable
GROUP BY visit_number, NAME
Matt
  • 14,906
  • 27
  • 99
  • 149
0

Join the table with a sub-query that returns each visit_number together with its max order_number:

SELECT distinct t1.*
FROM tablename t1
  JOIN (select visit_number, MAX(Order_number) as max_Order_number
        from tablename group by visit_number) as t2
  ON t1.visit_number = t2.visit_number and t1.Order_number = t2.max_Order_number

(Will return all rows if several different Names for a maximum order number.)

jarlh
  • 42,561
  • 8
  • 45
  • 63
0
select VISIT_NUMBER, ORDER_NUMBER, NAME
from (
select VISIT_NUMBER, ORDER_NUMBER, NAME, row_number() over(partition by VISIT_NUMBER order by ORDER_NUMBER desc) as ORDER_DESC
from TABLE
)
where ORDER_DESC = 1

This will return the max for each VISIT_NUMBER, even if the NAME changes

JohnHC
  • 10,935
  • 1
  • 24
  • 40