0

我想根据几个条件覆盖一个数字。

预期覆盖:
如果一个字符串(在我使用的示例中只是一个字母)在 3 列中出现至少 2 次并且数字列超过某个数字,则覆盖数值 如果另一个字符串在 3 列中出现至少 2次数值列多于某个其他数值,覆盖数值,否则保持数值不变。

我首先想到的方法有效,但前提是表格只有一行。这可以以某种方式扩展,以便它可以在更多行上工作吗?如果我的方法是错误的,请您指导我正确的方法吗?

请参阅SQL Fiddle

非常感谢任何帮助!

如果字母asection_1,section_2,section_3number >= 3中重复至少 2次,则用3 覆盖number或者如果字母b在section_1,section_2,section_3number >= 8中重复至少2次,则写8,否则留下编号不变

CREATE TABLE sections (
id int,
section_1 text,
section_2 text,
section_3 text,
number    int
 );

INSERT INTO sections VALUES
( 1, 'a',  'a',  'c', 5),
( 2, 'b',  'b',  'c', 9), 
( 3, 'b',  'b',  'c', 4); 

在此处输入图像描述

预期结果:
id 号
1 3
2 8
3 4

4

2 回答 2

1

你在寻找case表达吗?

select (case when (section_1 = 'a')::int + (section_2 = 'a')::int + (section_3 = 'a')::int >= 2 and
                  other_col > threshold
             then 'special'
        end)

你可以有额外的when条件。update如果您真的想更改值,请将其包含在其中。

于 2020-10-21T16:26:45.703 回答
1

一个典型的解决方案是使用横向连接来反透视:

select s.*, x.number as new_number
from sections s
cross join lateral (
    select count(*) number
    from (values (s.section_1), (s.section_2), (s.section_3)) x(section)
    where section = 'a'
) x;

这比重复条件表达式更具可扩展性,因为您只需要枚举子查询的values()行构造函数中的列。

于 2020-10-21T16:27:36.637 回答