sql - Add calculated column to existing table of max date grouped by id

Viewed 16

I have an existing table I have created and I would like to alter my table by creating a new calculated column which will obtain the max date by ID.

Multiple times a day, new data will flow into the table from a form input (web app). Every time the ID and datestamp are entered into the database, I would like the calculated column to update.

I created my table to interact with Powerapps web form:

CREATE TABLE [dbo].[test_table2](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [datestamp] [date] NULL,
 CONSTRAINT [tableId] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO

I have tried to create a column with something like this.....

SELECT id, datestamp FROM ( 
  SELECT id, datestamp, 
    RANK() OVER (PARTITION BY id ORDER BY datestamp DESC) max_date_id
    FROM test_table2
  ) where max_date_id = 1

I ultimately would like to alter the table so it updates automatically, but this code is just a query and also does not work. How can I achieve this?

0 Answers
Related