Postgresql,如何在CASE WHEN查询中调用特定值?

Postgresql, how to call a specific value in CASE WHEN query?

我有一个查询,我需要在 CASE WHEN 结构中使用两个数字参数(2012 年为 27133,2013 年为 32890),但这些参数是来自另一个 table 的值,即 [=11] =].

如何避免硬编码? 下面是我尝试过的:

CREATE TABLE total_srti_by_year (
maxsrti numeric NOT NULL,
year int NOT NULL,
PRIMARY KEY (year)
);

insert into total_srti_by_year 
select max(company_abc.srti), company_abc.year
from company_abc 
group by year

UPDATE company_abc as cm
SET cls = case 
            WHEN  cm.year = 2012 and cm.srti <= 27133*0.8 THEN 'A'
            WHEN  cm.year = 2012 and cm.srti <= 27133*0.95 THEN 'B'
            WHEN  cm.year = 2013 and cm.srti <= 32890*0.8 THEN 'A'
            WHEN  cm.year = 2013 and cm.srti <= 32890*0.95 THEN 'B'
END
FROM company_abc;

我认为你不需要中级 table。您可以自行加入 table 并同时更新它,如下所示:

update company_abc as c
set cls = case 
    when c.srti <= t.maxsrti * 0.8  then 'a'
    when c.srti <= t.maxsrti * 0.95 then 'b'        
end
from (
    select year, max(srti) as maxsrti
    from company_abc
    group by year
) t 
where c.year = t.year;

如果过滤掉您不想更新的行也可能是个好主意。为此,您可以调整 where 子句:

where c.year = t.year and c.srti <= t.maxsrti * 0.95

如果你有一个主键,比如 id,你也可以使用 window 函数而不是聚合:

update company_abc as c
set cls = case 
    when t.ratio <= 0.8  then 'a'
    when t.ratio <= 0.95 then 'b'        
end
from (
    select t.*, 
        1.0 * srti / max(srti) over(partition by year) as ratio
    from company_abc
) t 
where c.id = t.id and t.ratio <= 0.95