0

I would need a code for the following problem:

I have a table like this:

Employee Year Month Car
Tom 2021 9 Ford
Tom 2021 10 Ford
Tom 2021 11 Ford
Tom 2021 12 Renault
Tom 2022 1 Renault
Mark 2021 12 VW
Mark 2022 1 VW
Mark 2022 2 VW
Joe 2021 8 Opel
Joe 2021 9 Tesla
Joe 2021 10 Ferrari

And I would need the car used by the employee for the last possible date. So the result should be:

Employee Car
Tom Renault
Mark VW
Joe Ferrari

With:

select employee, max(year || month) from table.cars
group by employee

I get the max(date) for every employee, but I do not know how to join the cars to the max(date).

How can I get the result I want?

MT0
  • 143,790
  • 11
  • 59
  • 117
Danitri
  • 3
  • 1

3 Answers3

0

You can use ROW_NUMBER() analytic function such as

SELECT Employee, Car
  FROM (SELECT ROW_NUMBER() OVER 
                           (PARTITION BY Employee ORDER BY year DESC, month DESC) AS rn,
               c.*
          FROM cars c)
 WHERE rn = 1

provided that the data type of the year and month are of string type, then you can replace the part ORDER BY year DESC, month DESC with

ORDER BY TO_NUMBER(TRIM(year)) DESC, TO_NUMBER(TRIM(month)) DESC

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
-1
with t as
(
  select *,
        row_number() over (partition by employee order by year desc, month desc) rn
  from cars 
) 
select employee, car 
from t
where rn = 1
juergen d
  • 201,996
  • 37
  • 293
  • 362
-1

Try this:

select employee, car 
from ( 
        Select *, ROW_NUMBER(partition by employee order by year, month DESC) as row_number
        from cars
        )a
Where row_number = 1
Shu Rahman
  • 634
  • 1
  • 5
  • 15