SQL查詢按某欄位排序的最大值
阿新 • • 發佈:2019-01-07
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.插入測試資料
3.要查詢出相同id中日期最近的記錄,即: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');
--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和其他高階函式實現呢,留待以後研究吧。