【问题标题】:Filter records yearly, monthly quarterly or weekly每年、每月、每季度或每周过滤记录
【发布时间】:2021-04-06 17:32:25
【问题描述】:

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

Product(VARCHAR2) Created Date (Date) Quantity
A 3/5/2021 12:20:15 PM 20
B 3/5/2021 12:20:15 PM 30

应使用“创建日期”列每年、每月、每季度或每周(根据用户输入)进行过滤。

用户输入示例;

前 01:

年份:2020,季度:1(可能的值 1、2、3、4)

例如:02

年:2020,月:6,周:1(可能的值 1、2、3、4)

例如:03

年:2020,月:6

例如:04

年份:2020

如何使用 Oracle SQL 实现这一点?

谢谢!

干杯,女娲

【问题讨论】:

  • 附带说明:如果 week 是一个月的一周,则可能的值 1 到 4 仅涵盖前 28 天(假设第 1 周表示第 1 到 7 天等)。

标签: sql oracle


【解决方案1】:

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

  • 季度

年份是强制性的,其他是可选的。任务是检查给出了哪些条件并在查询中使用或不使用它们(例如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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多