假設這是你的表:
CREATE TABLE t
(
custid integer,
warranty_period integer,
purchase_timestamp date /* timestamp ? */
);
與此數據:
INSERT INTO t
(custid, warranty_period, purchase_timestamp)
VALUES
(1, 365, '03-01-2017'),
(2, 30, '03-04-2017'),
(3, 10, '25-05-2017'),
(4, 30, '20-05-2017'),
(5, 365, '04-06-2017'),
(6, 100, '18-06-2017'),
(7, 90, '30-06-2017'),
(8, 10, '05-07-2017'),
(9, 30, '09-07-2017'),
(10, 365, '17-07-2017') ;
你可以使用下面的SELECT
:
SELECT
custid,
purchase_timestamp + cast(warranty_period || ' days' AS interval) AS end_of_warranty
FROM
t
ORDER BY
custid ;
或
SELECT
custid,
purchase_timestamp + make_interval(days := warranty_period) AS end_of_warranty
FROM
t
ORDER BY
custid ;
,並得到
custid | end_of_warranty
-----: | :------------------
1 | 2018-01-03 00:00:00
2 | 2017-05-03 00:00:00
3 | 2017-06-04 00:00:00
4 | 2017-06-19 00:00:00
5 | 2018-06-04 00:00:00
6 | 2017-09-26 00:00:00
7 | 2017-09-28 00:00:00
8 | 2017-07-15 00:00:00
9 | 2017-08-08 00:00:00
10 | 2018-07-17 00:00:00
注意這一點的PostgreSQL知道如何添加的間隔日期(或時間戳),並返回一個時間戳。
要指定的時間間隔,你需要使用
cast(warranty_period || ' days' AS interval)
或
warranty_period * interval '1 day'
這是接近SQL標準,或使用
make_interval(days := warranty_period)
使用特定PostgreSQL date/time function。
你可以只還使用(簡單的)形式:
SELECT
custid,
purchase_timestamp + warranty_period AS end_of_warranty
FROM
t
ORDER BY
custid ;
,它依賴於一個事實,即有一個+
運營商(日期+整數)把整數作爲數天,並執行相同的操作。在這種情況下,purchase_timestamp
列應該是實際上是是日期,或者是CAST(... AS date)
。
檢查了所有在dbfiddle here
選項是你使用MySQL或PostgreSQL?日期操作和格式化的功能在兩個數據庫中都不相同。在* * *數據庫上運行的語句不太可能。 – joanolo
PostgreSQL。在Redshift DB上運行此查詢 –
Postgres –