请教高手一个SQL-按某字段汇总,查处最新内容

来源:百度知道 编辑:UC知道 时间:2024/05/23 20:24:35
有一张表格由三个字段组成,"日期","名称"和"内容".如:
日期 名称 内容
---------------------------------------
2009-1-1 名称A 内容1
2009-1-2 名称A 内容2
2009-1-3 名称A 内容3
2009-1-1 名称B 内容4
2009-2-1 名称B 内容5
2009-2-25 名称B 内容6
2008-1-1 名称C 内容7
2008-2-1 名称C 内容8

我现在需要查询出表中每个名称的最新内容,请问SQL该怎么写?

如接上例,我需要得到如下结果集:
日期 名称 内容
--------------------------------------
2009-1-3 名称A 内容3
2009-2-25 名称B 内容6
2009-2-1 名称C 内容8

假设表名为table1

select distinct(t1.名称), t1.日期,t1.内容 from table1 t1 ,(select 名称, max(日期) as 日期 from table1 group by 名称) t2 where t1.日期 = t2.日期 order by t1.名称

1、select 名称, max(日期) as 日期 from table1 group by 名称 取出不同名称的最大日期,假设是以日期最新为获取标准,得到结果为
名称 日期
名称A 2009-1-3
名称B 2009-2-25
名称C 2009-2-1

2、 将1语句所查询出的临时表设置别名t2

3、从table1(别名t1)中查询出所需要的内容、日期和名称(注意:distinct(t1.名称)可以防止当日期相同时,出现一对多的情况,出现多条重复语句)

4、where t1.日期 = t2.日期 order by t1.名称,这个就不用说了吧,条件和排序,t2临时表的意义就是作为t1的条件 ==;

3楼的语意是正确的。但是语法出错了
正确的写法为:
select distinct a.日期, a.名称,a.内容 from 表 a ,
(select 名称, max(日期) as 日期 from 表 group by 名称) b
where a.日期 = b.日期

写是能写,但我想问你,你内容什么样是最新的?最新的依据是什么?
这个不说明白的话,想写也写不出来

select a.*
from 表名 a ,
(select max(日期) 日期 from 表名 group by 名称) b
where a.日期 = b.日期

select a.日期, a.名称,a.内容 from 表 a ,
(select 名称, max(日期) from 表 group by 名称) b
where a.日期 = b.日期

看不懂你的