[英]How to select rows in TIMESTAMP column in Oracle SQL?
我在 Oracle SQL 中有如下表:
col1
-------------
22/01/15 16:45:05,657432556
21/12/22 11:01:33,234543456
21/10/13 10:15:45,437483674
21/11/12 11:22:01,315432223
“col1”列上方是 TIMESTAMP,我想
因此,我希望有如下内容:
col1 | col2
----------------------------------------
21/10/13 10:15:45,437483674 | 21/10/13
21/11/12 11:22:01,315432223 | 21/11/12
我怎样才能在 Oracle SQL 中做到这一点?
对于第二部分,您可以添加一个虚拟列 - 这样您就不必维护两个值 - 将时间戳转换为日期,或者保留时间部分:
alter table your_table add (col2 date generated always as (cast(col1 as date)));
COL1 COL2
-------------------------- -------------------
2022-01-15 16:45:05.657432 2022-01-15 16:45:05
2021-12-22 11:01:33.234543 2021-12-22 11:01:33
2021-10-13 10:15:45.437483 2021-10-13 10:15:45
2021-11-12 11:22:01.315432 2021-11-12 11:22:01
或截断到午夜:
alter table your_table add (col2 date generated always as (trunc(cast(col1 as date))));
COL1 COL2
-------------------------- -------------------
2022-01-15 16:45:05.657432 2022-01-15 00:00:00
2021-12-22 11:01:33.234543 2021-12-22 00:00:00
2021-10-13 10:15:45.437483 2021-10-13 00:00:00
2021-11-12 11:22:01.315432 2021-11-12 00:00:00
要限制日期,您需要确定“之间”对您意味着什么。 当您使用该月的第一天时,我假设您真的想要 10 月和 11 月的所有数据,而实际上从 12 月 1 日开始没有任何数据; 在这种情况下:
select * from your_table
where col1 >= timestamp '2021-10-01 00:00:00'
and col2 < timestamp '2021-12-01 00:00:00'
COL1 COL2
-------------------------- -------------------
2021-10-13 10:15:45.437483 2021-10-13 00:00:00
2021-11-12 11:22:01.315432 2021-11-12 00:00:00
如果你想在第一个正好包含午夜,那么让它<=
。 要包括那天的整个时间,make 是<
2 号午夜。
如果您想要特定 output 格式的结果,请更改您的客户端/会话设置,或显式转换为字符串(仅用于显示):
select to_char(col1, 'YY/MM/DD HH24:MI:SS,FF9') as col1,
to_char(col2, 'YY/MM/DD') as col2
from your_table
where col1 >= timestamp '2021-10-01 00:00:00'
and col2 < timestamp '2021-12-01 00:00:00'
COL1 COL2
--------------------------- --------
21/10/13 10:15:45,437483674 21/10/13
21/11/12 11:22:01,315432223 21/11/12
表格内容:
SQL> desc test
Name Null? Type
----------------------------------------- -------- ----------------------------
COL1 TIMESTAMP(6)
COL2 DATE
SQL> select * From test order by col1;
COL1 COL2
------------------------------ -------------------
13.10.21 10:15:45,437484
22.12.21 11:01:33,234543
15.01.22 16:45:05,657433
15.01.22 16:45:05,657433
SQL>
对于 1 ,一种选择是使用时间戳文字:
SQL> select * From test where col1 between timestamp '2021-10-01 00:00:00.000'
2 and timestamp '2021-12-01 00:00:00.000';
COL1 COL2
------------------------------ -------------------
13.10.21 10:15:45,437484
SQL>
对于 2 ,使用CAST
:
SQL> update test set col2 = cast (col1 as date);
4 rows updated.
SQL> select * from test order by col1;
COL1 COL2
------------------------------ -------------------
13.10.21 10:15:45,437484 13.10.2021 10:15:45
22.12.21 11:01:33,234543 22.12.2021 11:01:33
15.01.22 16:45:05,657433 15.01.2022 16:45:05
15.01.22 16:45:05,657433 15.01.2022 16:45:05
SQL>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.