0

タスクの開始日とタスクの終了日を含む Posgres のテーブルがあります。(当日 - 開始日) / (開始日 - 終了日) の間のレートとして、この tale に列を生成することができます。列は経過時間の % です。私はこのように試みますが、うまくいきません。

ALTER TABLE public.gantt_task
ADD COLUMN 
      percentage_progress 
GENERATED  ALWAYS AS (
(DATEDIFF("day", 
CURRENT_DATE,public.gantt_Tasks.start_date)) / DATEDIFF("day", public.gantt_Tasks.end_date ,public.gantt_Tasks.start_date)) 
STORED 
4

2 に答える 2

0

The manual says postgres only supports materialized (ie, stored) generated columns, which means the value is generated when the row is inserted or updated, which means it will use the insert/update date, not the CURRENT_DATE you want.

So, you need to create a view instead. This allows evaluating CURRENT_DATE at the date of the SELECT, not the INSERT/UPDATE, to generate columns.

CREATE VIEW foo AS SELECT *, 
  (CURRENT_DATE - public.gantt_Tasks.start_date)
  / (public.gantt_Tasks.end_date-public.gantt_Tasks.start_date)
  AS percentage_progress
FROM public.gantt_task

Note DATEDIFF is mysql syntax not postgres, and division by zero is not allowed, so if start_date and end_date can be identical then you'll have to modify the expression conditions depending on what you want. Also your expression will go over 100% when CURRENT_DATE is later than end_date. Perhaps something like:

least( 1.0, (CURRENT_DATE-start_date)/greatest( 1, end_date-start_date)::FLOAT )
于 2021-01-17T21:56:55.097 に答える