If you had an extra column in the data, call it just_date
, containing just the date (year, month, day) part of the values shown, then you'd write:
SELECT name, just_date, MAX(date)
FROM SomeAnonymousTable
GROUP BY name, just_date;
So, how do you get just the date portions of a 'date' that includes time pieces...
This gets DBMS-specific, and I didn't know the details for MySQL. However, a web search found me the same answer that @Ipfavreau commented - the DATE() function:
SELECT name, DATE(date) AS just_date, MAX(date)
FROM SomeAnonymousTable
GROUP BY name, just_date;
The question was clarified...the previous answer is only part of the answer.
The query above identifies the rows that must be selected; now we need to pull out the kw
column value that matches. We cannot just add kw
into the select-list because we'd also have to list it in the GROUP BY clause (in standard SQL, at any rate). So, we need to embed the grouping query into the FROM clause:
SELECT a.name, a.kw, a.date
FROM SomeAnonymousTable AS a,
(SELECT name, DATE(date) AS just_date, MAX(date)
FROM SomeAnonymousTable
GROUP BY name, just_date
) AS b
WHERE a.name = b.name
AND a.date = b.date;
The code above was untested on any DBMS. Note that it is a bad idea to use a keyword (type, and function name) as a column name. Even if it is allowed, it is confusing. Also, please remember to give the table a name next time.
Update: Now tested on IBM Informix Dynamic Server (IDS) 11.50. An amended version of the query works on table dg
, as noted in the edits to another answer. The 'date' column was renamed to upd_time
. For better or worse, IDS requires the positional notation (1, 2) in the GROUP BY clause.
SELECT a.name, a.kw, a.upd_time
FROM dg AS a,
(SELECT name, DATE(upd_time) AS just_date, MAX(upd_time) AS upd_time
FROM dg
GROUP BY 1, 2 -- name, DATE(upd_time)
) AS b
WHERE a.name = b.name
AND a.upd_time = b.upd_time;
This modified query yields what seem to be the correct results:
dg1 135 2008-10-16 23:05:09
dg1 213 2008-10-17 02:06:09
dg2 135 2008-10-16 22:05:09
dg2 213 2008-10-17 05:06:09
This working version shows an area where different DBMS work slightly differently. Sometimes you can use the column aliases (sometimes called 'display labels'; the names after AS in the select-list) inside the query, and sometimes you can't. It depends on the DBMS in question, and maybe also on the level of the SQL standard that is supported. The positional notation (GROUP BY 1, 2 -- and the similar ORDER BY 1, 2) is not the preferred notation where names work. But when names don't work, you have to use whatever it takes to get the job done.