在SQL中创建计算字段 [英] Creating calculated fields in sql

查看:121
本文介绍了在SQL中创建计算字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很初级,但是我找不到一个与之匹配的简洁示例.

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

我有三个领域; m1m2m3.我需要创建一个列或字段,这是它们三个的平均值.计算的字段将标题为就业".下面的代码就足够了吗?

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)

样本数据

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

期望的结果.

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

推荐答案

您非常亲密,它称为Computed Column

https://technet.microsoft. com/en-us/library/ms191250(v = sql.105).aspx

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

更新:

如果您想强制计算列的数据类型,则可以执行以下操作

If you would like to force data type for a computed column, you could do the following

ALTER TABLE dbo.tablename ADD Employment AS CAST((m1+m2+m3)/3 AS Numeric (9,0))

这篇关于在SQL中创建计算字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆