假设这是你的表:
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 –