简体   繁体   中英

sql multiple columns filtering duplicates by newest

I have a SQL query (sqlight3) that gives me tripels (name, value, date) of data.

select name, value, date from
"different things and conditions"
order by date desc

The result ist sorted by date and looks like this:

name | value | date
-------------------
a    | x     | 2015
b    | y     | 2014
a    | z     | 2013
b    | x     | 2012
c    | y     | 2011

Now I want the results filtered, so that every name is unique and I only get the newest (by date) triples. I expect the result

name | value | date
-------------------
a    | x     | 2015
b    | y     | 2014
c    | y     | 2011

How can I achieve this?

Most databases support ANSI standard window functions, so this can be done using row_number() :

select name, value, date
from (select t.*,
             row_number() over (partition by name order by date desc) as seqnum
      from . . .
     ) t
where seqnum = 1;

EDIT:

MySQL doesn't support row_number() . Here is another method:

select name,
       substring_index(group_concat(value order by date desc), ',', 1) as value
       max(date) as date
from . . .
group by name;

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