2

这是一个示例表

ID  STOREA  STOREB  STOREC   AB   BC   CA  ABC
--- ------- ------  -------  --   --  ---  ---
10    1       0       0
10    0       1       0
10    0       1       0
29    0       1       0 
29    0       0       1
29    1       0       0      

每行对应于在商店 A 或 B 或 C 进行的购买。客户 10 在 A 和 B 商店但不在 c 商店。所以我想要AB=1 BC=0 CA=0 ABC=0 所有 ID=10 行和 ID=29,他在所有 3 个商店,所以我需要AB=1 BC=1 CA=1 ABC=1ID=29 的所有行(使用 ORACLE SQL)

我想更新表中的列。

4

2 回答 2

4

这是您可以做到这一点的一种方法。我认为您不能JOINs在 Oracle 中使用 withUPDATE语句——但是,您可以通过使用来完成同样的事情MERGE

MERGE
INTO    yourtable
USING   (
          select id as idnew, 
            case when a + b = 2 then 1 else 0 end abnew,
            case when b + c = 2 then 1 else 0 end bcnew,
            case when a + c = 2 then 1 else 0 end acnew,
            case when a + b + c = 3 then 1 else 0 end abcnew
          from (
            select 
              id,
              max(case storea when 1 then 1 else 0 end)  A,
              max(case storeb when 1 then 1 else 0 end)  B,
              max(case storec when 1 then 1 else 0 end)  C
            from yourtable
            group by id
          ) a
        )
ON      (id = idnew)
WHEN MATCHED THEN
UPDATE
SET     ab = abnew, 
  bc = bcnew,
  ac = acnew,
  abc = abcnew

SQL 小提琴演示

于 2013-03-22T02:35:30.627 回答
2

以下是您可以如何做到这一点select

update (select id, storea, storeb, storec, AB as new_AB, BC as new_BC, AC as new_AC, ABC as new_ABC
        from t join
             (select id,
                     (case when max(storeA) = 1 and max(storeB) = 1 then 1 else 0 end) as AB,
                     (case when max(storeB) = 1 and max(storeC) = 1 then 1 else 0 end) as BC,
                     (case when max(storeA) = 1 and max(storeC) = 1 then 1 else 0 end) as AC,
                     (case when max(storeA) = 1 and max(storeB) = 1 and max(storeC) = 1 then 1 else 0 end) as ABC
              from t
              group by id
             ) tsum
             on t.id = tsum.id
            )
     set AB = new_AB, AC = new_AC, BC = new_BC, ABC = new_ABC;

我认为这可能有效:

select id, storea, storeb, storec, AB, BC, AC, ABC
from t join
     (select id,
             (case when max(storeA) = 1 and max(storeB) = 1 then 1 else 0 end) as AB,
             (case when max(storeB) = 1 and max(storeC) = 1 then 1 else 0 end) as BC,
             (case when max(storeA) = 1 and max(storeC) = 1 then 1 else 0 end) as AC,
             (case when max(storeA) = 1 and max(storeB) = 1 and max(storeC) = 1 then 1 else 0 end) as ABC
      from t
      group by id
     ) tsum
     on t.id = tsum.id
            )
     set AB = new_AB, AC = new_AC, BC = new_BC, ABC = new_ABC;
于 2013-03-22T02:25:49.283 回答