I have the following data.
--------------------------------------------------------------------------------
id | value_name | last_modified | system_id | value_data |
--------------------------------------------------------------------------------
1 | name1 | 2012-06-04 | 1 | aaa |
2 | name1 | 2012-02-04 | 1 | bbb |
3 | name1 | 2012-04-25 | 1 | ccc |
4 | name2 | 2012-07-04 | 1 | ddd |
5 | name2 | 2012-06-14 | 1 | eee |
6 | name3 | 2011-09-05 | 1 | qqq |
--------------------------------------------------------------------------------
Now I need to get only most recently modified values.
update
For the table above I want to get the following result
--------------------------------------------------------------------------------
id | value_name | last_modified | system_id | value_data |
--------------------------------------------------------------------------------
1 | name1 | 2012-06-04 | 1 | aaa |
4 | name2 | 2012-07-04 | 1 | ddd |
6 | name3 | 2011-09-05 | 1 | qqq |
--------------------------------------------------------------------------------
I searched a lot here and in google as well, but the solutions I was able to find doesn’t actually work. For example one of the proposed solutions is usign join.
SELECT
v.[id],
v.[system_id],
v.[value_name],
v.[value_data]
FROM
[values] v INNER JOIN
(
SELECT
v.[id],
MAX(v.[last_modified]) AS last_modified
FROM
[values] v
WHERE
v.[system_id] = 1
GROUP BY
v.[id]
) s
ON
v.[id] = s.[id]
But sub-query is grouped by id (which is unique), so it will not calculate max last modification dates.
I’m using SQLite and simple query like that works for me
SELECT
v.[id],
v.[system_id],
v.[value_name],
v.[value_data],
MAX(v.[last_modified]) AS last_modified
FROM
[values] v
WHERE
v.[system_id] = 1
GROUP BY
v.[value_name]
But I remember from Oracle that you can’t select fields that are not listed in either aggregate functions or in group by statement, so I’m not sure this is guaranteed to give me expected result. Any suggestions how to solve that?
Thanks in advance.
If
last_modifiedis unique per value_name, you can use this:If not, you will need to extract last id for last_modified grouped by value_name:
Disclaimer: not tested.