-2

I want to select from my FileList all different files using group by. But I want to get Back only the elements with the highest id. I only get the first entry back. How to fix this?

select * from files group by name;

This is my table-content...

 ID      NAME          DATE               USER 
1443 - /test.txt - 24 May 2013 12:56:15 - XX
1444 - /test.txt - 24 May 2013 12:54:41 - XX
1445 - /test.txt - 24 May 2013 12:53:38 - AB
1446 - /test.txt - 24 May 2013 12:44:32 - XX
1983 - /asdf.txt - 24 May 2013 13:46:32 - KS
Bill Karwin
  • 499,602
  • 82
  • 638
  • 795
bbholzbb
  • 1,742
  • 3
  • 17
  • 28

2 Answers2

0
select * from files 
where id in
(
  select max(id)
  from files
  group by name
)

or

select f.* 
from files f
inner join 
(
  select max(id) as id
  from files
  group by name
) x on x.id = f.id

SQLFiddle demo

juergen d
  • 195,137
  • 36
  • 275
  • 343
  • 1
    I don't think this syntax would be valid on an ANSI standard platform.. – Kermit May 24 '13 at 17:22
  • Really? Why? I can't see the problem. – juergen d May 24 '13 at 17:23
  • ANSI SQL requires that the select-list include the column(s) in the GROUP BY clause. So you would write the subquery: `(select name, max(id) as id from files group by name)` and that would be okay. – Bill Karwin May 24 '13 at 17:26
  • Nope, [I'm wrong](http://sqlfiddle.com/#!3/5aa5e/1). For some reason I thought that column in the `GROUP BY` must be in the column list. – Kermit May 24 '13 at 17:27
  • Yeah, MySQL is more permissive than strict ANSI SQL. MySQL lets you write some forms of ambiguous statements when using GROUP BY, and trusts you know what you're doing. :-) – Bill Karwin May 24 '13 at 17:28
  • 1
    @BillKarwin This still shouldn't work in MSSQL. Looks like this is valid. – Kermit May 24 '13 at 17:30
  • 1
    Aha - I'm wrong about this. You can have a select-list without the grouping column. Here's a reference on GROUP BY rules based on "SQL-99 Complete, Really": https://kb.askmonty.org/en/rules-for-grouping-columns/ But you can't have a select-list with non-grouping column unless it's inside a grouping function. E.g. `select a, b, max(c) from table group by a` makes b ambiguous. – Bill Karwin May 24 '13 at 18:00
-1

Use this:-

select *,max(id) from files group by name;
Vivek Sadh
  • 4,190
  • 2
  • 29
  • 47