我有以下代码:
update table
set
offer_id_02 = offer_id_03,
offer_id_03 = offer_id_04,
offer_id_04 = offer_id_05,
offer_id_05 = offer_id_06,
offer_id_06 = offer_id_07,
offer_id_07 = offer_id_08,
offer_id_08 = NULL
where offer_id_02 = offer_id_01;
update table
set
offer_id_03 = offer_id_04,
offer_id_04 = offer_id_05,
offer_id_05 = offer_id_06,
offer_id_06 = offer_id_07,
offer_id_07 = offer_id_08,
offer_id_08 = NULL
where offer_id_03 = offer_id_01 or offer_id_03 = offer_id_02;
update table
set
offer_id_04 = offer_id_05,
offer_id_05 = offer_id_06,
offer_id_06 = offer_id_07,
offer_id_07 = offer_id_08,
offer_id_08 = NULL
where offer_id_04 = offer_id_01 or offer_id_04 = offer_id_02 or offer_id_04 = offer_id_03;
update table
set
offer_id_05 = offer_id_06,
offer_id_06 = offer_id_07,
offer_id_07 = offer_id_08,
offer_id_08 = NULL
where offer_id_05 = offer_id_01 or offer_id_05 = offer_id_02 or offer_id_05 = offer_id_03 or offer_id_05 = offer_id_04;
update table
set
offer_id_06 = offer_id_07,
offer_id_07 = offer_id_08,
offer_id_08 = NULL
where offer_id_06 = offer_id_01 or offer_id_06 = offer_id_02 or offer_id_06 = offer_id_03 or offer_id_06 = offer_id_04 or offer_id_06 = offer_id_05;
update table
set
offer_id_07 = offer_id_08,
offer_id_08 = NULL
where offer_id_07 = offer_id_01 or offer_id_07 = offer_id_02 or offer_id_07 = offer_id_03 or offer_id_07 = offer_id_04 or offer_id_07 = offer_id_05 or offer_id_07 = offer_id_06;
update table
set
offer_id_08 = NULL
where offer_id_08 = offer_id_01 or offer_id_08 = offer_id_02 or offer_id_08 = offer_id_03 or offer_id_08 = offer_id_04 or offer_id_08 = offer_id_05 or offer_id_08 = offer_id_06 or offer_id_08 = offer_id_07;
本质上,我有一个包含客户的 SQL 表以及他们作为促销获得的 8 个优惠。由于逻辑错误,出现了一些重复的情况。为了解决这个问题,我“跳过”了重复的优惠并清空了 Offer_id_08 插槽。问题是,逻辑是不同的,具体取决于哪些报价彼此重复。我怎样才能以简洁的方式构建这个?
也许,作为第一步,您可以尝试使用 CASE 和组合 WHERE 将查询合并为一个大查询:
UPDATE table
SET offer_id_02 =
CASE
WHEN offer_id_02 = offer_id_01 THEN offer_id_03
ELSE offer_id_02
END,
offer_id_03 =
CASE
WHEN offer_id_03 = offer_id_01 OR offer_id_03 = offer_id_02 THEN offer_id_04
ELSE offer_id_03
END,
...
offer_id_08 = NULL
WHERE
offer_id_01 IN (offer_id_02, offer_id_03, offer_id_04, offer_id_05, offer_id_06, offer_id_07, offer_id_08)
OR offer_id_02 IN (offer_id_03, offer_id_04, offer_id_05, offer_id_06, offer_id_07, offer_id_08)
...
OR offer_id_07 = offer_id_08;
这是重新格式化(取消透视、展平)表格的简单方法,如 @JNevill 建议的那样,每个记录有 4 个重复属性用于说明。
create table the_table (
id serial,
attr_1 integer,
attr_2 integer,
attr_3 integer,
attr_4 integer
);
insert into the_table (attr_1,attr_2,attr_3,attr_4)
values
(10, 11, 12, 13),
(20, 21, 22, 23),
(30, 31, 32, 33);
select t.id, l.*
from the_table t
cross join lateral (
select 'attr_1', attr_1 union all
select 'attr_2', attr_2 union all
select 'attr_3', attr_3 union all
select 'attr_4', attr_4
) as l(attr_name, attr_value);