創建測試用表:
CREATE OR REPLACE VIEW v AS SELECT TO_DATE('2015-1-1 13:14:15', 'YYYY-MM-DD HH24:MI:SS') AS c FROM DUAL; SELECT * FROM v;
兩個date相減,得到的就是天數,乘以24就是小時,以此類推,可以計算出秒,如果要計算月份間隔,需要使用函數months_between。
SQL代碼如下:
SELECT 間隔天數, 間隔天數 * 24 AS 間隔小時, 間隔天數 * 24 * 60 AS 間隔分, 間隔天數 * 24 * 60 * 60 AS 間隔秒, MONTHS_BETWEEN(SYSDATE, c) AS 間隔月, MONTHS_BETWEEN(SYSDATE, c) / 24 AS 間隔年 FROM (SELECT c, SYSDATE - c AS 間隔天數 FROM v);
執行結果如下: