PostgreSQL 中是否有一个函数可以计算跨列的字符串匹配(按行)
Is there a function in PostgreSQL that counts string match across columns (row-wise)
我想根据一些条件覆盖一个数字。
预期覆盖:
如果一个字符串(在我使用的示例中只是一个字母)在 3 列中出现至少 2 次 和 数字列大于某个数字,覆盖数值 或
如果另一个字符串在 3 列中出现至少 2 次 and 数字列大于其他数字,覆盖数字值,else 保留数值不变。
我首先想到的方法有效,但前提是 table 有一行。这可以以某种方式扩展以便它可以在更多行上工作吗?如果我的方法是错误的,你能告诉我正确的方法吗?
请参阅 SQL Fiddle
非常感谢任何帮助!
如果字母 a 在 [ 中重复 至少 2 次=78=],section_2,section_3 and number >= 3 然后覆盖 number with 3 或者如果字母 b 重复 至少 [= section_1、section_2、section_3和数中的29=]2次>= 8 写入 8,否则保持 number 不变
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);
预期结果:
身份证号码
1 3
2 8
3 4
您是否在寻找 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
中。
一个典型的解决方案是使用横向连接来取消透视:
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()
行构造函数中的列。
我想根据一些条件覆盖一个数字。
预期覆盖:
如果一个字符串(在我使用的示例中只是一个字母)在 3 列中出现至少 2 次 和 数字列大于某个数字,覆盖数值 或
如果另一个字符串在 3 列中出现至少 2 次 and 数字列大于其他数字,覆盖数字值,else 保留数值不变。
我首先想到的方法有效,但前提是 table 有一行。这可以以某种方式扩展以便它可以在更多行上工作吗?如果我的方法是错误的,你能告诉我正确的方法吗?
请参阅 SQL Fiddle
非常感谢任何帮助!
如果字母 a 在 [ 中重复 至少 2 次=78=],section_2,section_3 and number >= 3 然后覆盖 number with 3 或者如果字母 b 重复 至少 [= section_1、section_2、section_3和数中的29=]2次>= 8 写入 8,否则保持 number 不变
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);
预期结果:
身份证号码
1 3
2 8
3 4
您是否在寻找 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
中。
一个典型的解决方案是使用横向连接来取消透视:
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()
行构造函数中的列。