0

I have a table with 2 columns (id, name) with following values:

id    name
---   ---
 1    John
 2    John 
 3    Mary
 4    Mary

For values that are repeated in 'name', I only want to select those rows which have maximum value in 'id'. So my desired output is:

id    name
---   ---
 2    John
 4    Mary

I tried following instructions from this link: Fetch the row which has the Max value for a column but couldn't get it to work.

This is the query I'm using:

select 
    name, id 
from
    (select 
         name, max(id) over (partition by name) max_ID 
     from sometable) 
where 
    id = max_ID

But I'm getting this error:

Incorrect syntax near the keyword 'where'.

Any ideas what I'm doing wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
90abyss
  • 7,037
  • 19
  • 63
  • 94

3 Answers3

4

If you alias your subquery you will avoid the syntax error... try putting "AS MyTable" after your closing parenthesis

select name, id 
FROM ( select name, max(id) over (partition by name) max_ID from sometable ) AS MyTable 
where id = max_ID

This might be simpler though:

SELECT name, MAX(id) FROM tablename GROUP BY name
Shoeless
  • 666
  • 1
  • 5
  • 20
  • Worth noting that the alias syntax can be "...from sometable) MyTable" or with an "AS" like so, "...from sometable) AS MyTable" – Shoeless May 20 '16 at 20:03
1

Your subquery has no mandatory alias

.. 
FROM ( select name, max(id) over (partition by name) max_ID from sometable )  t -- alias missing 
..
Serg
  • 22,285
  • 5
  • 21
  • 48
1

You are using an alias for an aggregate function in where this is wrong.

Using having you can select the name with more then one row

 select * from my_table where id in (  
 select max(id) from my_table where name in 
 (
   select   name
   from  my_table 
   having count(*) >1 
   group by name )) ;
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107