Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query, distinct rows needed

I have the following table structured like this:

row structure

So basically as you can see, the department goes through name changes every couple of years. Look at number 16 for example. I want a select query that will only get the name when the date is the greatest. How do I do that?

like image 448
masfenix Avatar asked Jun 25 '10 17:06

masfenix


People also ask

How do I SELECT distinct rows in SQL?

The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

Why you shouldn't use SELECT distinct?

As a general rule, SELECT DISTINCT incurs a fair amount of overhead for the query. Hence, you should avoid it or use it sparingly. The idea of generating duplicate rows using JOIN just to remove them with SELECT DISTINCT is rather reminiscent of Sisyphus pushing a rock up a hill, only to have it roll back down again.

Do you need a group by when using distinct?

GROUP BY is required if you're aggregating data, but in many cases, DISTINCT is simpler to write and read if you aren't aggregating data.

Does distinct affect query performance?

Yes, the application needs to compare every record to the "distinct" records cache as it goes. You can improve performance by using an index, particularly on the numeric and date fields.


2 Answers

select ID, Name from departments o 
where o.thedate=
  (select max(i.thedate) from departments i where o.id=i.id)
like image 62
Ken Bloom Avatar answered Oct 11 '22 07:10

Ken Bloom


SELECT ID, 
First(Name) AS FirstOfName, First(DateChange) AS FirstOfDateChange
FROM departments
GROUP BY ID
ORDER BY First(DateChange) DESC;
like image 37
Conrad Frix Avatar answered Oct 11 '22 07:10

Conrad Frix