oracle 如何连接表以获得记录,如左连接[关闭]

dgenwo3n  于 2023-04-20  发布在  Oracle
关注(0)|答案(1)|浏览(121)

已关闭,该问题需要details or clarity,目前不接受回答。
**想要改进此问题?**通过editing this post添加详细信息并澄清问题。

2天前关闭。
Improve this question
我有下面记录的表1。

H_ID   STATUS
1001   Approved
1002   Approved
1003   Approved

第二个表有以下记录

H_ID   L_NO    ITEM_ID   LOCATION   QTY
1001    1      220050    S1         5
1002    1      220050    S2         1
1002    2      230050    S2         4
1003    1      220050    S3         3
1003    2      230050    S3         2
1003    3      240050    S3         5

需要你的帮助来写sql查询得到下面的输出

ITEM_ID       LOCATION  QTY
220050         S1        5
220050         S2        1
220050         S3        3
230050         S1        0
230050         S2        4
230050         S3        2
240050         S1        0
240050         S2        0
240050         S3        5

我是新的SQL,所以需要你的帮助,建立一个查询,以获得输出。在预期中感谢。

gmxoilav

gmxoilav1#

一个选项(非常简单)是交叉连接不同的位置和项,然后将该组合外连接到第二个表。
样本数据:

SQL> with
  2  t1 (h_id) as
  3    (select 1001 from dual union all
  4     select 1002 from dual union all
  5     select 1003 from dual
  6    ),
  7  t2 (h_id, item_id, location, qty) as
  8    (select 1001, 220050, 'S1', 5 from dual union all
  9     select 1002, 220050, 'S2', 1 from dual union all
 10     select 1002, 230050, 'S2', 4 from dual union all
 11     select 1003, 220050, 'S3', 3 from dual union all
 12     select 1003, 230050, 'S3', 2 from dual union all
 13     select 1003, 240050, 'S3', 5 from dual
 14    ),

查询从这里开始:

15  locations as
 16    (select distinct location from t2),
 17  items as
 18    (select distinct item_id from t2)
 19  select i.item_id, l.location, nvl(b.qty, 0) qty
 20  from locations l cross join items i
 21       left join t2 b on b.location = l.location
 22                      and b.item_id = i.item_id
 23  order by i.item_id, l.location;

   ITEM_ID LOCATION          QTY
---------- ---------- ----------
    220050 S1                  5
    220050 S2                  1
    220050 S3                  3
    230050 S1                  0
    230050 S2                  4
    230050 S3                  2
    240050 S1                  0
    240050 S2                  0
    240050 S3                  5

9 rows selected.

SQL>

相关问题