sql - Getting the maximum value of records -


i having table called withdrawals has : name, year, period, amount.

ex:

name   year    period    amount -------------------------------- jim    2010    1         100 jim    2009    4         99 jim    2009    3         17 kim    2007    2         234 ryu    2008    5         555 

i stuck can't latest value name & amount has recent year latest period.

i tried use query:

select max(year), max(period), name withdrawarls 

but got wrong results.

so, how can correct values:

jim, 2010, 1, 100 kim, 2007, 2, 234 ryu, 2008, 5, 555. 

in mysql , postgresql:

select  t.*    (         select  distinct name            mytable         ) td join    mytable t on      (t.year, t.period) =         (         select  year, period            mytable ti           ti.name = td.name         order                 name desc, year desc, period desc         limit 1         ) 

in sql server:

select  t.*    (         select  distinct name            mytable         ) td cross apply         (         select  top 1 *            mytable ti           ti.name = td.name         order                 year desc, period desc         ) t 

in sql server , oracle:

select  *    (         select  t.*, row_number() on (partition name order year desc, period desc) rn            mytable         ) t   rn = 1 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -