1、查询两个日期之间的数据。
假设有表Table1,其创建表的sql语句为:
create table Table1(
StationID NUMBER(10) Primary key,
Year NUMBER(4) not null,
Month NUMBER(2) not null,
Day NUMBER(2) not null);
现在我需要查在'2005-01-01'至'2006-01-01'之间的所有数据,遇到的主要问题是:表Table1中的日期信息分别存放在三个字段(Year,Month,Day)中,怎样实现这一查询呢?
答案如下:
SQL>select * from Table1 where to_date(concat(concat(concat(concat(year,'-'),lpad(month,2,0)),'-'),lpad(DAY,2,0)),'yyyy-mm-dd')
between to_date('2005-01-01','yyyy-mm-dd') and to_date('2006-01-01','yyyy-mm-dd');
答案解释:
(1)使用concat函数连接Year,Month,Day三个字段,从而构造一个新的字符串(包含年、月、日信息),使其格式为:'年-月-日';
(2)使用lpad函数补足月份及天数,使之都是二位,这是因为to_date函数的第一个参数是必须为'yyyy-mm-dd'类型;
(3)使用between and来确定范围。