首頁 > 軟體

SQL常用日期查詢語句及顯示格式設定

2022-04-10 16:00:04

1.查詢當前年、月、周相關時間

1.1.查詢當前年份

SELECT TO_CHAR(SYSDATE,'YYYY') AS YEAR FROM DUAL--查詢當前年份
SELECT TO_CHAR(SYSDATE,'YYY') AS YEAR FROM DUAL--查詢當前年份後兩位
SELECT TO_CHAR(SYSDATE,'YY') AS YEAR FROM DUAL--查詢當前年份最後兩位
SELECT TO_CHAR(SYSDATE,'Y') AS YEAR FROM DUAL--查詢當前年份最後一位

1.2.查詢當前年份第幾天

SELECT TO_CHAR(SYSDATE,'DDD') AS DAYS FROM DUAL

1.3.查詢當前月份第幾天

SELECT TO_CHAR(SYSDATE,'DD') AS DAYS FROM DUAL

1.4.查詢當前周的星期幾

SELECT TO_CHAR(SYSDATE,'dy') AS WEEK FROM DUAL
SELECT TO_CHAR(SYSDATE,'day') AS WEEK FROM DUAL

1.5.查詢當前年的第幾天:

SELECT TO_CHAR(SYSDATE,'DDD') AS DAYS FROM DUAL

2.查詢當前第幾季度

SELECT TO_CHAR(SYSDATE,'Q') AS JD FROM DUAL

3.查詢當前在一年內是第幾周

SELECT TO_CHAR(SYSDATE,'IW') AS WEEKNUM FROM DUAL
SELECT TO_CHAR(SYSDATE,'WW') AS WEEKNUM FROM DUAL
SELECT TO_CHAR(SYSDATE,'W') AS WEEKNUM FROM DUAL

4.查詢當前某年某月有多少天

SELECT TO_CHAR(last_day(to_date('2019/02/01','YYYY/MM/DD')),'DD') AS MONTH_DAYS_NUMBER FROM DUAL

5.查詢當前的日期格式

SELECT TO_CHAR(SYSDATE,'YYYY/MM/DD') AS MONTH FROM DUAL--獲取當前日期的'YYYY/MM/DD'格式:2020/01/02
SELECT TO_CHAR(SYSDATE,'YYYYMMDD') AS MONTH FROM DUAL--獲取當前日期的'YYYYMMDD'格式:20200102
SELECT TO_CHAR(SYSDATE,'YYYYMMDD HH:MI:SS') AS now FROM DUAL--獲取當前時間,精確到秒的12小時制格式:20200102 03:18:25
SELECT TO_CHAR(SYSDATE,'YYYYMMDD HH24:MI:SS') AS now FROM DUAL--獲取當前時間,精確到秒24小時制的格式:20200102 15:18:13
SELECT TO_CHAR(SYSDATE,'YYYY/MM/DD HH24:MI:SS:PM:DY') AS now FROM DUAL--獲取當前時間的格式,顯示上、下午和星期幾:2020/01/02 15:17:59:下午:星期四

6.查詢距離當前時間一段時間間隔的時間,當前時間之前用“-”當前時間之後用“+”

SELECT TO_CHAR(SYSDATE, 'YYYY/MM/DD HH24:MI:SS') AS NOW,TO_CHAR(SYSDATE - INTERVAL '7' second,'YYYY/MM/DD HH24:MI:SS') AS PAST FROM DUAL --查詢當前時間的7秒前時間
SELECT TO_CHAR(SYSDATE, 'YYYY/MM/DD HH24:MI:SS') AS NOW,TO_CHAR(SYSDATE - INTERVAL '7' minute,'YYYY/MM/DD HH24:MI:SS') AS PAST FROM DUAL --查詢當前時間的7分鐘前時間
SELECT TO_CHAR(SYSDATE, 'YYYY/MM/DD HH24:MI:SS') AS NOW,TO_CHAR(SYSDATE - INTERVAL '7'hour ,'YYYY/MM/DD HH24:MI:SS') AS PAST FROM DUAL --查詢當前時間的7小時前時間
SELECT TO_CHAR(SYSDATE, 'YYYY/MM/DD HH24:MI:SS') AS NOW,TO_CHAR(SYSDATE - INTERVAL '7'day ,'YYYY/MM/DD HH24:MI:SS') AS PAST FROM DUAL --查詢當前時間的7天前時間
SELECT TO_CHAR(SYSDATE, 'YYYY/MM/DD HH24:MI:SS') AS NOW,TO_CHAR(SYSDATE - INTERVAL '7'month ,'YYYY/MM/DD HH24:MI:SS') AS PAST FROM DUAL --查詢當前時間的7月前時間
SELECT TO_CHAR(SYSDATE, 'YYYY/MM/DD HH24:MI:SS') AS NOW,TO_CHAR(SYSDATE - INTERVAL '7'year ,'YYYY/MM/DD HH24:MI:SS') AS PAST FROM DUAL --查詢當前時間的7年前時間
SELECT TO_CHAR(SYSDATE, 'YYYY/MM/DD HH24:MI:SS') AS NOW,TO_CHAR(SYSDATE - 8*INTERVAL '7'hour ,'YYYY/MM/DD HH24:MI:SS') AS PAST FROM DUAL --查詢當前時間引數年、月、日、時、分、秒乘以一個數位倍數之前的時間

到此這篇關於SQL常用日期查詢語句及顯示格式設定的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com