Oracle SQL:如何根据条件插入行?

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

我有一张table申请人:
| ID|接收|
| --|--|
| 1 |食品|
| 1 |租金援助|
| 1 |汽车票|
| 2 |食品|
| 2 |租金援助|
| 3 |食品|
| 4 |汽车票|
| 5 |null|
正如你所看到的,我有一个申请人表,申请人已经收到了不同数量的好处。但现在我需要检查这个候选人表,并确保所有申请人都得到所有3个好处:食物房租补助还有车票申请人也不能两次获得这种福利。如何在Oracle SQL中实现这一点?
注意:我有Benefits表,其中的benefitsMap到唯一的id(food = 100,rent assistance = 101,bus ticket = 102)。为了可读性,我写了名字而不是数字。
我看了各种声明,如合并和存在,但不能看到这将如何适用于我的情况。

deikduxw

deikduxw1#

可以使用MERGE语句和PARTITION艾德ed OUTER JOIN

MERGE INTO applicant dst
USING (
  WITH benefits (benefit) AS (
    SELECT 'food'            FROM DUAL UNION ALL
    SELECT 'rent assistance' FROM DUAL UNION ALL
    SELECT 'bus ticket'      FROM DUAL
  )
  SELECT a.ROWID AS rid,
         a.pID,
         b.benefit
  FROM   benefits b
         LEFT OUTER JOIN applicant a
         PARTITION BY (a.pID)
         ON (a.received = b.benefit)
) src
ON (src.rid = dst.ROWID)
WHEN NOT MATCHED THEN
  INSERT (pID, Received) VALUES (src.pID, src.benefit);

其中,对于样本数据:

CREATE TABLE applicant (pID, Received) AS
SELECT 1, 'food' FROM DUAL UNION ALL
SELECT 1, 'rent assistance' FROM DUAL UNION ALL
SELECT 1, 'bus ticket' FROM DUAL UNION ALL
SELECT 2, 'food' FROM DUAL UNION ALL
SELECT 2, 'rent assistance' FROM DUAL UNION ALL
SELECT 3, 'food' FROM DUAL UNION ALL
SELECT 4, 'bus ticket' FROM DUAL UNION ALL
SELECT 5, null FROM DUAL;

然后,在MERGE之后,该表包含:
| PID|接收|
| --|--|
| 1 |食品|
| 1 |租金援助|
| 1 |汽车票|
| 2 |食品|
| 2 |租金援助|
| 3 |食品|
| 4 |汽车票|
| 5 |(空值)|
| 2 |汽车票|
| 3 |汽车票|
| 3 |租金援助|
| 4 |食品|
| 4 |租金援助|
| 5 |汽车票|
| 5 |食品|
| 5 |租金援助|
提琴

相关问题