Creating calculated fields in sql

Tim Wilcox picture Tim Wilcox · Sep 7, 2017 · Viewed 7k times · Source

This will seem rudimentary but I can't find a concise example online that matches up.

I have three fields; m1, m2, and m3. I need to create a column or field that is the average of them three. The calculated field would be titled employment. Would the following code be suffice?

ALTER TABLE dbo.tablename ADD Employment AS Select ((m1+m2+m3)/3)

Sample data

m1   20    20    30
m2   15    17    25
m3   60    77    13

desired result.

Name        m1    m2    m3   Employment
Auto body    20    20    30     23
Auto Parts   15    17    25     19
Auto Sales   60    77    13     50

Answer

Yeou picture Yeou · Sep 7, 2017

You can check Computed Columns

CREATE TABLE t1(
    col1 int,
    col2 int,
    col3 int,
    col4 as (col1*col2*col3)/3

)

insert into t1  values(1,2,3)

select * from t1