简体   繁体   中英

SQL query to get only the latest value by Date

I have the following two tables:

Table1 {T1ID, Name}

Table2 {T2ID, T1ID, Date, Value}

Date is of type DATE.

and I am looking for a SQL query to fetch only the latest value (by Date) for each T1ID for which the Name matches a specific string.

SELECT`Table2`.`T1ID`,
    `Table2`.`Value`,
    `Table2`.`Date`, 
    `Table1`.`Name`,
    FROM `Table1` 
    INNER JOIN `Table2` ON `Table2`.`T1ID` = `Table1`.`T1ID`
    WHERE `Table1`.`Name` LIKE 'Smith'

but this returns the value for several dates for the same T1ID.

How do I get only the latest value by Date?


Edit: I am using MySQL 5.5.8

If I've understodd the question correctly: Assuming MySQL:

SELECT`Table2`.`T1ID`,
`Table2`.`Value`,
`Table2`.`Date`, 
`Table1`.`Name`
FROM `Table1` 
INNER JOIN `Table2` ON `Table2`.`T1ID` = `Table1`.`ID`,
(SELECT T1ID, MAX(Date) AS 'Date' FROM Table2 GROUP BY T1ID) Table3
WHERE 
`Table3`.`T1ID` = `Table2`.`T1ID`
AND
`Table3`.`Date` = `Table2`.`Date`
AND
`Table1`.`Name` LIKE 'Smith'

EDIT: Updated the code to bring back the correct result set. Removed MSSQL answer as it wasn't relevant

You have two options.

select t1.t1id, max(t1.Name) Name, max(t2.date) Date, 
(select Value from table2 t22 
 where t22.date = max(t2.date) and t22.t1id = t2.t1id) Value
from table1 t1 left join table2 t2 on t1.t1id = t2.t1id
where Name like '%Smith%'
group by t2.t1id order by 2

OR

select mx.t1id, mx.Name, mx.Date, t2.Value
from 
(
select t1.t1id, max(t1.Name) Name, max(t2.date) Date
from table1 t1 left join table2 t2 on t1.t1id = t2.t1id
where Name like '%Smith%'
group by t2.t1id
) mx left join table2 t2 on (t2.t1id = mx.t1id and t2.date = mx.date)
order by 2

Both will produce the same result. The first one takes less code but you might have performance issues with a huge set of data. The second one takes a little more code, but it is also a little more optimized. Notes on the JOIN option:

  • If you go LEFT JOIN (as the example shows), items in Table1 with no correspondent records on Table2 will be displayed in the result, but the values in columns Date and Value will be NULL
  • If you go INNER JOIN, items in Table1 with no correspondent records on Table2 will not be displayed .

EDIT

I missed one of the requirements, which was the Name matching a specific string. The code is now updated. The '%' acts like a wildcard, so it will match names like 'Will Smith' and 'Wail Smithers'. If you want a exact match, remove the wildcards ('%').

将此添加到您的SQL:

ORDER BY 'Date' DESC LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM