基于另外两列获取第三列数据

时间:2013-03-22 02:21:14

标签: sql oracle oracle-sqldeveloper

这是一个示例表

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个,所以对于ID = 29的所有行,我需要AB=1 BC=1 CA=1 ABC=1(使用ORACLE SQL)

我想更新表格中的列。

2 个答案:

答案 0 :(得分:4)

这是一种可以做到这一点的方法。我不认为您可以在JOINs语句中使用Oracle中的UPDATE - 但是,您可以使用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 Fiddle Demo

答案 1 :(得分: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;