views:

72

answers:

4

Hey guys, 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?

A: 

What is the primary key for this table? This does a subquery the same table with a name comparison.

SELECT
    id,
    name,
    date
FROM table
WHERE name = (SELECT TOP 1 name
              FROM table AS subtable
              WHERE subtable.name = table.name
              ORDER BY date DESC)
BC
+5  A: 
select ID, Name from departments o 
where o.thedate=
  (select max(i.thedate) from departments i where o.id=i.id)
Ken Bloom
Thankyou, worked beautifully.
masfenix
+1  A: 
SELECT ID, 
First(Name) AS FirstOfName, First(DateChange) AS FirstOfDateChange
FROM departments
GROUP BY ID
ORDER BY First(DateChange) DESC;
Conrad Frix
+1 for Alt. Solution. The group by ID threw me, but in this case, it is the duplicate data field.
Jeff O
A: 

SELECT d.* FROM Departments d INNER JOIN (SELECT pk FROM Departments GROUP BY ID HAVING theDate=MAX(theDate)) m ON m.pk=d.pk WHERE [Name]="Department"

Speed Nick
This is better than the accepted answer because...?
David-W-Fenton