2015-07-04 34 views
2

我试图让下面的表格如何在sql中获得不同的结果?

id | name | created_on 
1 | xyz | 2015-07-04 09:45:14 
1 | xyz | 2015-07-04 10:40:59 
2 | abc | 2015-07-05 10:40:59 

的不同结果,我想不同的ID与最新created_on手段以下结果

1 | xyz | 2015-07-04 10:40:59 
2 | abc | 2015-07-05 10:40:59 

如何获得上述由SQL查询结果?

回答

4

试试这个:

Select id, name, max(created_on) as created_on from table group by id 
+0

Thanks.Superb !!!!!! – Ace

+0

欢迎您:)如果有用,请接受答案:) –

1

尝试:

select id,max(name), max(created_on) from table_name group by id 

附加说明:

当它出现时,你的表是不是标准化。也就是说,您在此表中存储name以及id。所以,你可以同时拥有这两行:

id | name | created_on 
    1 | a | 12-12-12 
    1 | b | 11-11-11 

如果状态不是逻辑模型中的可能,您应该通过拆分该表分成两个独立的表重新设计你的数据库;一个拿着id-name关系,而另一个持有id-created_on关系:

table_1 (id,name) 
table_2 (id,created_on) 

现在,让每个ID最后created_on:

select id,max(created_on) from table_2 

,如果你想查询持有name

select t1.id, t1.name, t2.created_on from table_1 as t1 inner join 
(select id, max(created_on) as created_on from table_2) as t2 
on t1.id=t2.id 
0

假设ID /名称始终是一对:

select id, name, max(created_on) 
from table 
group by id, name; 

将两者都包含在group by中更安全。当它不是唯一的表格时,我也发现它命名为id这一列是误导性的。

0

您可以使用关键字DISTINCT

SELECT DISTINCT 
相关问题