我想根据某些情况/条件在现有SQL表中添加具有默认值的新列。
我想知道是否有可能。如果是,怎么办?如果不是,为什么?
替代方案:
一种选择是创建列,然后更新,但是这里的方法是不可能的。
让我们考虑一下下表
╔════╦══════════════╗
║ ID ║ Age ║
╠════╬══════════════║
║ 1 ║ 0.166667 ║
║ 2 ║ 0.125 ║
║ 3 ║ 13 ║
║ 4 ║ 19 ║
║ 5 ║ 45 ║
║ 6 ║ 59 ║
║ 7 ║ 60 ║
║ 8 ║ 64 ║
╚════╩══════════════╝
所需的输出是这样的:
╔════╦══════════════╦═══════════╗
║ ID ║ Age ║ AgeGroup ║
╠════╬══════════════╬═══════════╣
║ 1 ║ 0.166667 ║ NewBorn ║
║ 2 ║ 0.125 ║ NewBorn ║
║ 3 ║ 13 ║ Teen ║
║ 4 ║ 19 ║ Teen ║
║ 5 ║ 45 ║ Adult ║
║ 6 ║ 59 ║ Adult ║
║ 7 ║ 60 ║ Elder ║
║ 8 ║ 64 ║ Elder ║
╚════╩══════════════╩═══════════╝
我已经研究了这篇文章,但这仅用于“添加列默认值”
编辑:这是上面表格的SQL脚本,其中包含要测试的用户的表和数据。
您可以尝试一下。基本上有两种方法可以实现此目的。
在表架构中添加列
据我了解,您想在表架构中添加一列作为您共享的给定链接。您可以使用case
语句为计算值添加列。
编辑:更正语法错误
alter table yourtable
add AgeGroup as (case
when Age < 2 then 'New Born'
when Age < 19 then 'Teen'
when Age < 45 then 'Young'
when Age > 60 then 'Adult'
else 'Invalid'
end);
要么
建立检视
您可以为其创建视图,并在需要时使用它。
Create View TableResult
As
Select Id, Age, case Age
WHEN Age < 2 then 'New Born'
WHEN Age < 19 then 'Teen'
WHEN Age < 45 then 'Young'
WHEN Age > 60 then 'Adult'
else 'Invalid'
end as AgeGroup
End
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句