2017-07-28 21 views
2

我有一個表格,其中的天數爲(custid,purchase_timestamp (dd-mm-yyyy), warranty_period)。我需要purchase_time和warranty_period的總和。我可以如何爲此編寫SQL。我可以從數據庫中的另一列中讀取間隔值嗎?

我試圖

SELECT DATE_SUB(purchase_timestamp, INTERVAL warranty_period DAY); 

,但它不工作。請建議

|custid | warranty_period | purchase_timestamp 
    |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 
+0

選項是你使用MySQL或PostgreSQL?日期操作和格式化的功能在兩個數據庫中都不相同。在* * *數據庫上運行的語句不太可能。 – joanolo

+0

PostgreSQL。在Redshift DB上運行此查詢 –

+0

Postgres –

回答

0

假設這是你的表:

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

+0

這工作,謝謝 –

0

SELECT DATE_SUB(STR_TO_DATE(purchase_timestamp,'%d-%m-%Y'), INTERVAL warranty_period DAY);

你可以試試上面的代碼。

這裏我添加了功能STR_TO_DATE

使用此功能,您必須將您的字符串轉換爲DATE

否則你DATE場必須'YYYY-MM-DD' format.Then,僅在MySQL引擎考慮您的字符串的日期。

您可以嘗試以上查詢。

這是Fiddle demo

+0

中沒有'date_sub()'在「warranty_period」處或其附近出現錯誤ERROR:語法錯誤位置 –

+0

@PreetiKumar您必須放上表名並嘗試執行。 –

+0

@PreetiKumar你可以檢查http://sqlfiddle.com/#!9/b8bbcd/1 –

相關問題