我有2张桌子TAB1和TAB2。两者都有3列每个SEGMENT,LEVEL和VALUE。以下是两个表格的数据:
TAB1
SEGMENT LEVEL VALUE
----------------------------------
SEG1 1 1000
SEG1 2 900
SEG1 3 800
SEG2 1 4000
SEG2 2 3000
SEG2 3 1000
SEG3 1 5000
SEG3 2 3500
SEG3 3 2200
TAB2
SEGMENT LEVEL VALUE
----------------------------------
SEG1 1 2000
SEG1 2 1800
SEG1 3 1200
SEG2 1 3000
SEG2 3 2500
SEG4 1 10000
SEG4 2 8100
SEG4 3 2900
因为你可以看到我在表和一些段中总共有四个段SEG1,SEG2,SEG3和SEG4,两个表中都没有风险等级。对于SEGMENT和LEVEL列的组合,我希望两个表中的VALUE最小。查询的输出应该是这样的:
SEGMENT LEVEL VALUE
----------------------------------
SEG1 1 1000
SEG1 2 900
SEG1 3 800
SEG2 1 3000
SEG2 2 3000
SEG2 3 1000
SEG3 1 5000
SEG3 2 3500
SEG3 3 2200
SEG4 1 10000
SEG4 2 8100
SEG4 3 2900
我尝试通过Full outer join实现它,但输出不是我的预期:
SELECT t1.SEGMENT, t1.LEVEL, t2.SEGMENT, t2.LEVEL, LEAST(t1.VALUE, t2.VALUE)
FROM TAB1 t1
FULL OUTER JOIN TAB2 t2
ON t1.SEGMENT = t2.SEGMENT
AND t1.LEVEL = t2.LEVEL;
非常感谢任何帮助。数据库是Oracle。
答案 0 :(得分:3)
试试这个,
select segment,level,min(value) value from (
select segment,level,value from tab1
UNION ALL
select segment,level,value from tab2
) d group by segment,level