【发布时间】:2021-12-16 12:30:06
【问题描述】:
我有两张表,TBL_A 和 TBL_B。
TBL_A 如下所示:
TBL_B 如下所示:
我需要根据在 TBL_A 中找到的与特定状态相对应的 DATETIME 信息更新 TBL_B,因此:
when status = 'CLAIMED' put DATETIME in CLAIMED_DATETIME
when status = 'BOUGHT' put DATETIME in BOUGHT_DATETIME
when status = 'RETURNED' put DATETIME in RETURNED_DATETIME
我有这个问题:
MERGE INTO TBL_B B
USING (
SELECT * FROM TBL_A
PIVOT(MIN(ACCOUNT_REWARD_UPDATED_AT_DATETIME) FOR ACCOUNT_REWARD_STATUS IN ('claimed', 'bought', 'returned'))
AS P (number_id, country, amount, currency, file_tp, ingestion_time, claimed, bought, returned)
) A ON (
A.number_id = B.number_id,
and A.country = B.country,
and A.amount = B.amount,
and A.currency = B.currency,
and A.file_tp = B.file_tp
and A.ingestion_time = B.ingestion_time
)
WHEN MATCHED THEN
UPDATE SET
B.CLAIMED_DATETIME = IFF(A.claimed IS NOT NULL, A.claimable , '2999-12-31 23:59:5'),
B.BOUGHT_DATETIME = IFF(A.bought IS NOT NULL, A.claimed , '2999-12-31 23:59:5'),
B.RETURNED_DATETIME = IFF(A.reverted IS NOT NULL, A.reverted, '2999-12-31 23:59:5');
当我加入 ALL 列时,file_tp 和 ingestion_time 对于每个状态(认领、购买和退回)都是不同的,而其余列对于每个状态都是相同的。当我运行上面的查询时,它只更新 1 个 DATE,而不是全部。我意识到这是因为我无法加入 FILE_TP 和 INGESTION_TIME,因为每个状态都不同。但是,当我从连接条件中删除这些时,我收到一个错误:
MERGE INTO TBL_B B
USING (
SELECT * FROM TBL_A
PIVOT(MIN(DATETIME) FOR STATUS IN ('claimed', 'bought', 'returned'))
AS P (number_id, country, amount, currency, file_tp, ingestion_time, claimed, bought, returned)
) A ON (
A.number_id = B.number_id,
and A.country = B.country,
and A.amount = B.amount,
and A.currency = B.currency,
--and A.file_tp = B.file_tp
--and A.ingestion_time = B.ingestion_time
)
WHEN MATCHED THEN
UPDATE SET
B.CLAIMED_DATETIME = IFF(A.claimed IS NOT NULL, A.claimable , '2999-12-31 23:59:5'),
B.BOUGHT_DATETIME = IFF(A.bought IS NOT NULL, A.claimed , '2999-12-31 23:59:5'),
B.RETURNED_DATETIME = IFF(A.reverted IS NOT NULL, A.reverted, '2999-12-31 23:59:5');
错误:
Duplicate row detected during DML action Row Values:
有谁知道我该如何解决这个问题?
【问题讨论】:
-
“当我运行上面的查询时,它只更新 1 个 DATE,而不是全部”——你的意思是有多个行需要更新,它们共享相同的 (number_id, country 、金额、货币)?
标签: sql snowflake-cloud-data-platform snowflake-schema