我们有六个配置单元表,其示例(example)结构如下(其中每个表有数百万条商户记录)
Table1
MerchntId ,field1, field2
Table2
MerchantId, field3,field4
Table3
MerchantId, field5,field6,field7
Table4
MerchantId, field8,field9,field10
Table5
MerchantId, field11, field12, field13
等等
要求是创建一个水平布局,以获取所有唯一的商户,其中至少有一个字段对一个merchantid有价值,而merchantid可能存在于其他表中,也可能不存在于其他表中。(对于商户,可能存在于其他表中,也可能不存在于其他表中)
最终表格merchntid,字段1,字段2,字段3,字段4,
字段5、字段6、字段7、字段8、字段9、字段10、字段11、字段12、字段13
输出应该是连接后的样子
i) 101 abc def ghi
ii) 102 ghj fert hyu ioj khhh jjh ddd aas fff kkk fff vvv ff
对于情况(i),只有三个字段有值;对于情况(ii),所有字段都有值
为此,我们在merchantid上对两个表进行完全外部联接,以此类推,然后创建最终的表
有没有更好的办法?
例如,我目前的方法
SELECT distinct
(case when a.MerchntId IS NOT NULL then a.MerchntId else (case when
b.MerchntId IS NOT NULL
then b.MerchntId else '' end ) end ) as MerchntId,
(case when a.field1 IS NOT NULL then a.field1 else '' end ) as field1,
(case when a.field2 IS NOT NULL then a.field2 else '' end ) as field2,
(case when b.field3 IS NOT NULL then b.field3 else '' end ) as field3,
(case when b.field4 IS NOT NULL then b.field4 else '' end ) as field4
from Table1 a
full outer join Table2 b
ON a.MerchntId = c.MerchntId;
表3和表4的完全外部联接,然后这两个表的完全外部联接来创建最终的表
2条答案
按热度按时间erhoui1w1#
union all 6表,用空值替换缺少的字段。然后使用最小值或最大值按商品进行聚合:
在此之后,如果需要,可以应用逻辑,将null替换为“”
wljmcqd82#
我看不到任何其他选项,因为您的需求显式转换为完全外部联接。但是,您的查询可以通过使用
COALESCE
以及NVL
:还有,我不知道你为什么用
distinct
在您的查询中。