带键的表是日期和序列号

问题描述 投票:-1回答:2

预先感谢您的帮助。

我有一个SQL表,看起来像这样。

enter image description here

日期和序列号是一个复合键。意思是不能有一个具有相同日期和相同serial_number的元组。现在,我想获得每个serial_number的最新日期(事务)。我怎样才能做到这一点?这是我试过的,但它给了我一些重复。

SELECT DATE_FORMAT(`t1`.date,'%m-%d-%y') as date  , `t1`.serial_number
FROM table1 `t1`
WHERE date IN (SELECT MAX(date) FROM table1 GROUP BY serial_number)
order by `t1`.date desc, `t1`.serial_number asc;
mysql sql max
2个回答
0
投票

您需要相关子查询,而不仅仅是子查询:

SELECT DATE_FORMAT(t.date,'%m-%d-%y') as date, t.serial_number
FROM table1 t
WHERE t.date = (SELECT MAX(t1.date) 
                FROM table1 t1 
                WHERE t1.serial_number = t.serial_number
               )
order by t.date desc, t.serial_number asc;

0
投票

您可以在max_date上为serial_number使用内部联接

> SELECT DATE_FORMAT(`t1`.date,'%m-%d-%y') as date  
>     , `t1`.serial_number FROM `table` `t1` INNER JOIN (
>     SELECT serial_number, MAX( DATE_FORMAT(`T`.date,'%m-%d-%y')) max_date 
>     FROM `table` T
>     GROUP BY serial_number ) T ON T.serial_number = `t1`.serial_number AND T.max_date  = DATE_FORMAT(`t1`.date,'%m-%d-%y')
> 
> order by `t1`.date desc, `t1`.serial_number asc;
© www.soinside.com 2019 - 2024. All rights reserved.