我正在尝试将dollar_amount值替换为具有这些条件的现有值。每当status = 201604中的status ='Open'且period = 201605中的status ='Active'时,我希望将dollar_amount替换为10.从下面的SQL查询中,我可以在case语句中使用1列(状态)两次?
以下是示例数据:
create table atable1 (
id int,
status string,
period int,
dollar_amount decimal(18,2) );
insert into atable1 values (1234, "Open", "201604", 0);
insert into atable1 values (1234, "Active", "201605", 9.99);
insert into atable1 values (2222, "Open", "201604", 0);
insert into atable1 values (2222, "Active", "201605", 9.99);
原始数据如下:
id status period dollar_amount
1234 Open 201604 0
1234 Active 201605 9.99
2222 Open 201604 0
2222 Active 201605 9.99
更改后,我希望数据看起来像:
id status period dollar_amount
1234 Open 201604 0
1234 Active 201605 10
2222 Open 201604 0
2222 Active 201605 10
以下是我尝试的查询:
select
id,
status,
period,
case when
(status = 'Open' and period = 201604)
and (status = 'Active' and period = 201605)
then 10
else dollar_amount
end dollar_amount_value
答案 0 :(得分:1)
您的查询已结束。但是,您需要将when
表达式中的case
条件更改为
case when status = 'Open' and period = 201604 then 10
when status = 'Active' and period = 201605 then 10
else dollar_amount
end
您所拥有的表达式的问题在于,您要检查一行上的两个状态和句点值,这些值始终失败。因此,您应该将它们分成单独的when
条件。