The data defination for my table:
\d quote
Table "public.quote"
Column | Type | Collation | Nullable | Default
--------+---------------+-----------+----------+-----------------------------------
ticker | text | | |
date | date | | |
open | numeric(7,2) | | |
high | numeric(7,2) | | |
low | numeric(7,2) | | |
close | numeric(7,2) | | |
volume | numeric(7,2) | | |
id | integer | | not null | nextval('quote_id_seq'::regclass)
Indexes:
"quote_pkey" PRIMARY KEY, btree (id)
I can create new column into a new table:
SELECT *,
CASE WHEN ROW_NUMBER() OVER (PARTITION BY ticker ORDER BY ticker,date asc) >= 12
THEN AVG(close) OVER (PARTITION BY ticker ORDER BY ticker ROWS BETWEEN 11 PRECEDING AND CURRENT ROW)
END AS short_ma INTO new_quote FROM quote;
Can i add the new column short_ma in the previous table quote,instead of creating new table new_quote with alter command or other way?
The alter command structure maybe something like:
ALTER TABLE quote ADD COLUMN short_ma DECIMAL(7, 2) GENERATED ALWAYS AS () STORED;
My try failed :
ALTER TABLE quote ADD COLUMN short_ma DECIMAL(7, 2) GENERATED ALWAYS AS (
SELECT CASE WHEN ROW_NUMBER() OVER (PARTITION BY ticker ORDER BY ticker,date asc) >= 12
THEN AVG(close) OVER (PARTITION BY ticker ORDER BY ticker ROWS BETWEEN 11 PRECEDING AND CURRENT ROW)
END AS short_ma FROM quote) STORED;