注:凡是标明"不准确"的,都不建议用,因为这个语句有缺陷,最后一天的数据最能查到00:00:00的数据,00:00:01~23:59:59的就查不到了。
测试用的表
create table dateTest(
id number(18),
thedate date
);
插入数据略
当天的
(1)
Select * From dateTest t
Where trunc(t.thedate)= trunc(Sysdate);
(2)
select * from dateTest t
where to_char(t.thedate,'yyyyMMdd')=to_char(sysdate,'yyyyMMdd');
本周的(国外)
trunc(Sysdate,‘d’)这是这个星期的第一天即周日。
Next_day(trunc(sysdate,‘d’),7) 这是这个星期的最后一天即周六。
(1)
Select * From dateTest t
Where trunc(t.thedate)>=trunc(Sysdate,'d')
AND trunc(t.thedate)<= Next_day(trunc(sysdate,'d'),7);
(2)
Select * From dateTest t
Where t.thedate >=trunc(sysdate,'day') and t.thedate<trunc(sysdate,'day')+7;
(3).不准确
Select * From dateTest t
Where t.thedate >=trunc(sysdate,'day') and t.thedate<=trunc(sysdate,'day')+6;
本周的(国内)
国内的一周一般都是从周一算起,到周日结束。
因为Next_day()函数的第二个参数最多为7,不能用8,所以只能是如下写法
Select * From dateTest t
Where t.thedate >=trunc(sysdate,'day')+1 and t.thedate<trunc(sysdate,'day')+8;
本月的
(1).
select * from dateTest t
where to_char(t.thedate,'yyyyMM')=to_char(sysdate,'yyyyMM');
(2).
select * from dateTest t
where t.thedate >=TRUNC(SYSDATE, 'MM') and t.thedate<trunc(last_day(SYSDATE))+1;
(3).不准确
select * from dateTest t
where t.thedate >=TRUNC(SYSDATE, 'MM') and t.thedate<=last_day(SYSDATE);
今年的
(1)
select * from dateTest t
where to_char(t.thedate,'yyyy')=to_char(sysdate,'yyyy');
(2).
select * from dateTest t
where t.thedate>=trunc(sysdate,'yyyy') and t.thedate<add_months(trunc(sysdate,'yyyy'),12);
(3).不准确
select * from dateTest t
where t.thedate>=trunc(sysdate,'yyyy') and t.thedate<=add_months(trunc(sysdate,'yyyy'),12)-1;
今年每月的数据总量
select to_char(t.thedate,'MM') as month,count(1) as countNum
from dateTest t
where to_char(t.thedate,'yyyy')=to_char(sysdate,'yyyy')
group by to_char(t.thedate,'MM')
order by to_char(t.thedate,'MM') asc
函数详解
select trunc(sysdate) from dual;--当天00:00:00 同等于select trunc(sysdate,'dd') from dual;
select trunc(sysdate,'d') from dual;--本周第一天(周日)00:00:00
select next_day(trunc(sysdate,'d'),7) from dual;--本周最后一天(周六)00:00:00
select trunc(sysdate,'MM') from dual;--本月1号00:00:00
select trunc(sysdate,'yyyy') from dual;--今年1月1号00:00:00
select add_months(trunc(sysdate,'yyyy'),12) from dual;--明年1月1号00:00:00(今年1月1号00:00:00加上12个月)
版权声明:本文为qq_20481125原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。