Vertica:如何通过减去另外两个列来创建一个新列?

Vertica: How to create a new column by subtracting two other columns?

我有一个名为 Start_End 的 Vertica table,例如:

|   name |    Started |      Ended |
------------------------------------
| Albert | 1970-01-16 | 1970-06-01 |
|  Barry | 1992-05-01 | 1992-07-14 |
|  Carol | 2001-03-16 | 2001-06-03 |

它有大约 100,000 行。

如何使用 months_betweenEnded 中减去 Started

结果 table 看起来像:

|   name |    Started |      Ended | Month_diff |
-------------------------------------------------
| Albert | 1970-01-16 | 1970-06-01 |           4|
|  Barry | 1992-05-01 | 1992-07-14 |           2|
|  Carol | 2001-03-16 | 2001-06-03 |           2|

以下将添加一个空白栏:

ALTER TABLE Start_End
ADD COLUMN Month_diff INTEGER

如何使用months_between

您似乎想要日期之间有完整的月份。它认为这是:

select months_between(date_trunc('month', ended), date_trunc('month', started)) - 1 as month_diff

检查这里: https://www.vertica.com/docs/9.3.x/HTML/Content/Authoring/SQLReferenceManual/Functions/Date-Time/MONTHS_BETWEEN.htm?zoom_highlight=MONTHS%20BETWEEN

查明 MONTHS_BETWEEN() 的行为(何时为 return INTEGER,何时为 return FLOAT,最后一天的行为等)是你需要的那个。 否则,您可能希望先 DATE_TRUNC() 这两个操作数,例如@Gordon Linoff 建议的那样。或者改用 TIMESTAMPDIFF(month, ...) : https://www.vertica.com/docs/9.3.x/HTML/Content/Authoring/SQLReferenceManual/Functions/Date-Time/TIMESTAMPDIFF.htm?zoom_highlight=timestampdiff

也就是说,试试这个尺码:

ALTER TABLE start_end
ADD month_diff INTEGER DEFAULT MONTHS_BETWEEN(ended,started)

祝你好运...