每年、每月、每季度或每周过滤记录



我需要编写一个SQL来过滤基于日期类型列的记录。

创建日期(日期(20
产品(VARCHAR2( 数量
A 2021年5月3日下午12:20:15
B 2021年5月3日下午12:20:15 30

这样看;用户可以请求四个标准:

  • 季度

年份是强制性的,其他年份是可选的。任务是检查给定了哪些标准,并在查询中使用或不使用它们(例如where (:month is null or extract(month from created_date) = :month)(。

查询:

select *
from mytable
where extract(year from created_date) = :year
and (:quarter is null or to_number(to_char(created_date, 'q')) = :quarter)
and (:month is null or extract(month from created_date) = :month)
and (:week is null or trunc(extract(day from created_date) / 7) + 1 = :week)

最新更新