用于链接多个表的Oracle SQL子查询

时间:2017-07-06 15:59:26

标签: oracle subquery

我有3个不同的数据集

数据1:

ID  Rank_down
1   
2   
3   

DATA2:

ID  From    To
1   AB     CD
2   EF     JK
3   PQ  PQ

DATA3:

From/To  rank
  AB     1
  CD     2
  EF     3
  JK     5
  PQ     9

我需要根据ID是否从较高级别移动到较低级别(1是最低级别)来将字段rank_down填充为Y / N。这必须在Oracle SQl中完成。我是这个编程的新手,因此发现编写子查询很困难。

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

尝试:

select t.*, 
      CASE WHEN 
           ( SELECT "RANK" FROM DATA_3 d
             WHERE d.From_To = t."FROM"
           )
           >
           ( SELECT "RANK" FROM DATA_3 d
             WHERE d.From_To = t."TO"
           )
        THEN 'Y' ELSE 'N' END
        As rank_down 
from data_2 t;

答案 1 :(得分:0)

我只是没有关注,所以我会尝试一些SQL,看看这是否让我们更接近......

此选择是否以选择的方式提供所需的结果? (我可能有Y / N倒置)

SELECT ID, Case when D3a.Rank < D3b.Rank then 'N' 
                when D3a.Rank > D3b.Rank then 'Y'
                when D3a.Rank = D3b.Rank then 'N'
                end as Rank_down
FROM data2 D2
INNER JOIN data3 D3a
 on D3a.From_To = D2.From
INNER JOIN data3 D3b
 on D3b.From_To = D2.To

如果是这样,我们只需要根据它进行更新。

UPDATE Data1 d1
INNER JOIN (    SELECT ID, Case when D3A.Rank < D3b.Rank then 'N' 
                    when D3A.Rank > D3B.Rank then 'Y'
                    when D3A.Rank = D3B.Rank then 'N'
                    end as Rank_down
    FROM data2 D2
    INNER JOIN data3 D3a
     on D3a.From_To = D2.From
    INNER JOIN data3 D3b
     on D3B.From_To = D2.To) B
on B.ID = d1.ID 
set d1.Rank_down = B.Rank_Down