【问题标题】:How to pick specific date from a field of type timestamp in Oracle如何从 Oracle 时间戳类型的字段中选择特定日期
【发布时间】:2022-12-08 00:51:19
【问题描述】:

您好我正在尝试创建一个查询,该查询将在 oracle 中的特定日期销售平板电脑。字段数据类型是时间戳。

这是查询

SELECT 
  Order_detail.order_detail_id,
  product_name AS product,
  Product_categ_type.product_categ_type AS category,
  Order_line.qty AS qty,
  order_date
FROM Product, Order_detail, Order_line, Product_categ_type
WHERE Order_detail.order_detail_id = Order_line.order_detail_id
  AND Product.product_id = Order_line.product_id
  AND Product.product_categ_type_id = 3
  AND Product_categ_type.product_categ_type LIKE 'TB%'
  AND order_date = TO_DATE('2022-12-02' ,'yyyy,mm,dd')

查询有效,但没有返回任何数据,我认为问题在于我如何选择日期

-- INSERT INTO PRODUCT TABLE
INSERT INTO Product (product_id,product_categ_type_id,product_name,price,stock_qty) VALUES (174,1,'iWatch',454,183);

INSERT INTO Product (product_id,product_categ_type_id,product_name,price,stock_qty) VALUES (194,3,'Samsung Galaxy Tab',398,114);

INSERT INTO Product (product_id,product_categ_type_id,product_name,price,stock_qty) VALUES (139,1,'Fitness Tracker',312,122);

INSERT INTO Product (product_id,product_categ_type_id,product_name,price,stock_qty) VALUES (150,3,'iPad',366,189);

-- INSERT INTO PRODUCT CATEGORY TABLE

INSERT INTO Product_categ_type (product_categ_type_id,product_categ_type) VALUES (1,'AC');
INSERT INTO Product_categ_type (product_categ_type_id,product_categ_type) VALUES (2,'SP');
INSERT INTO Product_categ_type (product_categ_type_id,product_categ_type) VALUES (3,'TB');

-- INSERT INTO Order detail

INSERT INTO Order_detail (order_detail_id,product_id,customer_id,emp_id) VALUES (144,150,196,113);
INSERT INTO Order_detail (order_detail_id,product_id,customer_id,emp_id) VALUES (183,139,140,197);
INSERT INTO Order_detail (order_detail_id,product_id,customer_id,emp_id) VALUES (172,194,185,113);

-- INSERT INTO Order line

INSERT INTO Order_line (product_id,order_detail_id,qty) VALUES (150,144,1);
INSERT INTO Order_line (product_id,order_detail_id,qty) VALUES (139,183,5);
INSERT INTO Order_line (product_id,order_detail_id,qty) VALUES (194,172,1);

【问题讨论】:

  • 您需要匹配日期在字符串中的拼写方式。还要确保截断您尝试匹配的日期。试试AND TRUNC(order_date) = TO_DATE('2022-12-02' ,'YYYY-MM-DD')
  • “字段数据类型为时间戳。”哪个领域?我看到您有一个针对 order_date = TO_DATE('2022-12-02' ,'yyyy,mm,dd') 的过滤器,但您的示例数据中没有 order_date。

标签: sql oracle oracle-sqldeveloper


【解决方案1】:

使用 24 小时范围:

AND order_date >= DATE '2022-12-02'
AND order_date <  DATE '2022-12-03'

或者,您可以使用 TRUNC 将列截断回同一天的午夜,这样您就不必担心时间部分:

AND TRUNC(order_date) = DATE '2022-12-02'

但是,在这种情况下,Oracle 将无法在 order_date 列上使用任何索引,而需要在 TRUNC(order_date) 上使用基于函数的索引,因此通常最好使用范围。

【讨论】:

    猜你喜欢
    • 2015-05-14
    • 2019-06-20
    • 2021-10-31
    • 2012-12-11
    • 2018-09-24
    • 2013-11-17
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    相关资源
    最近更新 更多