合并这些数据集以获得所需格式的最佳方法是什么?

时间:2019-04-20 00:04:05

标签: join union

做一些ELT工作...
将这些数据集组合为所需输出形式的最佳方法是:

数据集A:

| project_id1 | types1 |  
A, apple  
B, banana  

数据集B:

| project_id1 | project_id2 | types2 |  
A, 15, strawberry    
A, 25, onion  
B, 5, peach  

所需结果:

| project_id1 | project_id2 | types |  
A, 15, strawberry  
A, 15, apple  
A, 25, onion  
A, 25, apple  
B, 5, peach  
B, 5, banana  

这种组合形式有名称吗?

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式获取该信息:

表格

create table da (
    project_id1 char(1),
    types1 varchar(100)
);

insert into da values
('A', 'apple'),
('B', 'banana');

create table db (
    project_id1 char(1),
    project_id2 int,
    types2 varchar(100)
);

insert into db values
('A', 15, 'strawberry'),
('A', 25, 'onion'),
('B', 5, 'peach');

查询

select * from (

    select da.project_id1, db.project_id2, da.types1 as types
    from da
    inner join db on da.project_id1 = db.project_id1

    UNION ALL

    select db.project_id1, db.project_id2, db.types2 as types
    from db
) x

order by project_id1, project_id2, types desc;

结果

project_id1 project_id2 types
A                 15    strawberry
A                 15    apple
A                 25    onion
A                 25    apple
B                  5    peach
B                  5    banana

示例

https://rextester.com/ISQA20343

我不知道这种数据合并的名称。