1.建表
-- Create table create table FRUIT ( id VARCHAR2(20), name VARCHAR2(20), class VARCHAR2(20), count VARCHAR2(20), buydate VARCHAR2(20) ) tablespace USERS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited );
insert into fruit (ID, NAME, CLASS, COUNT, BUYDATE) values ('1', '苹果', '水果', '10', '2011-7-1'); insert into fruit (ID, NAME, CLASS, COUNT, BUYDATE) values ('1', '桔子', '水果', '20', '2011-7-2'); insert into fruit (ID, NAME, CLASS, COUNT, BUYDATE) values ('1', '香蕉', '水果', '15', '2011-7-3'); insert into fruit (ID, NAME, CLASS, COUNT, BUYDATE) values ('2', '白菜', '蔬菜', '12', '2011-7-1'); insert into fruit (ID, NAME, CLASS, COUNT, BUYDATE) values ('2', '青菜', '蔬菜', '19', '2011-7-2');3.要查询出相同id中日期最近的记录,即:
--1 1 香蕉 水果 15 2011-7-3 --2 2 青菜 蔬菜 19 2011-7-2实现思路:常规思路为根据id进行分组查询各分组的日期最大值,之后筛选符合条件的记录就行了,查询SQL如下:
select * from fruit where (id,buydate) in (select id,max(buydate) from fruit group by id);使用到了in
本例也可以使用exists来实现:
select * from FRUIT t where not exists(select * from FRUIT where id=t.id and buydate>t.buydate);
在这里只想说,in和exists的原理相似,二者应该是能够实现相同的查询效果的,只是写法不同罢了。另外,本例是否能够通过rownum和其他高级函数实现呢,留待以后研究吧。