Sql 每年、每月、每季度或每周筛选记录

Sql 每年、每月、每季度或每周筛选记录,sql,oracle,Sql,Oracle,我需要编写一个SQL来根据日期类型列过滤记录 产品(VARCHAR2) 创建日期(日期) 量 A. 2021年3月5日12:20:15下午 20 B 2021年3月5日12:20:15下午 30 这样看,;用户可以请求四个标准: 年 四分之一 月 周 年份是强制性的,其他年份是可选的。任务是检查给定的条件以及在查询中使用或不使用它们(例如,,其中(:month为null或extract(month from created_date)=:month)) 查询: select * from m

我需要编写一个SQL来根据日期类型列过滤记录

产品(VARCHAR2) 创建日期(日期) 量 A. 2021年3月5日12:20:15下午 20 B 2021年3月5日12:20:15下午 30
这样看,;用户可以请求四个标准:

  • 四分之一
年份是强制性的,其他年份是可选的。任务是检查给定的条件以及在查询中使用或不使用它们(例如,
,其中(:month为null或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)

另请注意:如果周是一个月的一周,则1到4的可能值仅涵盖前28天(如果周#1表示第1到7天等)。