使用case语句在SQL中创建新变量

时间:2018-03-27 15:36:45

标签: sql

初学者SQL问题:如何在表中插入新的分类变量?

在Oracle SQL Developer中运行以下代码后:

create table test (
  memberid varchar(10),
  sex char(1),
  healthcost float(10)
  );

insert into test (memberid, sex, healthcost)
values ('A0003','M',25000);
insert into test (memberid, sex, healthcost)
values ('A0002','F',55000);
insert into test (memberid, sex, healthcost)
values ('A0001','M',10000);

alter table test
add healthcost_catg varchar(20);

insert into test (healthcost_catg)
select case when healthcost > 20000 then '> $20,000' as healthcost_catg
       else '<= $20,000' as healthcost_catg
end  
from test

我收到以下错误消息:

Error at Command Line : 18 Column : 54
Error report -
SQL Error: ORA-00905: missing keyword
00905. 00000 -  "missing keyword"
*Cause:    
*Action:

1 个答案:

答案 0 :(得分:3)

列别名应该在案例之后。

insert into test (healthcost_catg)
select case when healthcost > 20000 then '> $20,000'
       else '<= $20,000' end as healthcost_catg
from test

此外,我认为您需要UPDATE,而不是INSERT

update t set
healthcost_catg =  case when healthcost > 20000 then '> $20,000' else '<= $20,000'end  
from test t