将表与Oracle SQL合并

cig3rfwq  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(113)

我有两张table
| 项目|SPEC|
| --|--|
| 一|A1-1|
| B| B1-1|
| AZ| A1-1|
| BZ| B1-1|
| 项目|股票|
| --|--|
| 一| 1 |
| B| 2 |
| AZ| 3 |
| BZ| 4 |
我想把这两张表合并合并为一张:
| 项目|SPEC|库存1|库存2|
| --|--|--|--|
| 一|A1-1| 1 | 3 |
| B| B1-1| 2 | 4 |

wb1gzix0

wb1gzix01#

与您发布的样本数据(作为图像)

SQL> with
  2  t1 (item, spec) as
  3    (select 'A', 'A1-1' from dual union all
  4     select 'B', 'B1-1' from dual union all
  5     select 'C', 'C1-1' from dual union all
  6     select 'AZ','A1-1' from dual union all
  7     select 'BZ','B1-1' from dual union all
  8     select 'CZ','C1-1' from dual
  9    ),
 10  t2 (item, stock) as
 11    (select 'A', 1 from dual union all
 12     select 'B', 2 from dual union all
 13     select 'C', 5 from dual union all
 14     select 'AZ',3 from dual union all
 15     select 'BZ',4 from dual union all
 16     select 'CZ',6 from dual
 17    )

一个选项-产生所需的结果-是 double-join第二个表和第一个表的item列:一次获取MIN库存值,另一次获取MAX库存值:

18  select
 19    min(a.item) item,
 20    a.spec,
 21    min(b.stock) stock1,
 22    max(c.stock) stock2
 23  from t1 a join t2 b on a.item = b.item
 24            join t2 c on a.item = c.item
 25  group by a.spec
 26  order by a.spec;

IT SPEC     STOCK1     STOCK2
-- ---- ---------- ----------
A  A1-1          1          3
B  B1-1          2          4
C  C1-1          5          6

SQL>

相关问题