SQL查询按某字段排序的最大值

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
  );

2.插入测试数据

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和其他高级函数实现呢,留待以后研究吧。



你可能感兴趣的:(sql,in,exists)