合并查询返回ORA

合并查询返回ORA,第1张

合并查询返回ORA

如果您看到我在两个查询中都使用了distinct,那么行的重复不是问题。

您可能有重复的数据与其他列一起使用时

DISTINCT
,不能保证您具有
IdToUpdate
唯一性。
看:

CREATE TABLE #MyTable(IdToUpdate INT, LogSetIdToUpdateTo INT);INSERT INTO #MyTable VALUES (1,1), (1,2), (2,1),(3,1);SELECT DISTINCT IdToUpdate, LogSetIdToUpdateToFROM #MyTable;

**[
LiveDemo
](https://data.stackexchange.com/stackoverflow/query/387950)**

你会得到

IdToUpdate
两次。检查您的数据:

with cte AS (  select distinct nullLogSetId.Id as IdToUpdate,       knownLogSetId.LogSetId LogSetIdToUpdateTo  from MyTable knownLogSetId   join MyTable nullLogSetId    on knownLogSetId.IdentifierType = nullLogSetId.IdentifierType    and knownLogSetId.Identifier = nullLogSetId.Identifier   where     knownLogSetId.IdentifierType = 'DEF'    and knownLogSetId.LogSetId >= 0     and nullLogSetId.LogSetId = -1)SELECt IdToUpdate, COUNT(*) AS cFROM cteGROUP BY IdToUpdateHAVINg COUNT(*) > 1;

一种可行的方法是使用聚合函数,

(MAX/MIN)
而不是
DISTINCT

merge into MyTableusing(  select nullLogSetId.Id as IdToUpdate,         MAX(knownLogSetId.LogSetId) AS LogSetIdToUpdateTo   from MyTable knownLogSetId   join MyTable nullLogSetId    on knownLogSetId.IdentifierType = nullLogSetId.IdentifierType    and knownLogSetId.Identifier = nullLogSetId.Identifier   where     knownLogSetId.IdentifierType = 'DEF'    and knownLogSetId.LogSetId >= 0     and nullLogSetId.LogSetId = -1  GROUP BY nullLogSetId.Id) on (Id = IdToUpdate)when matched thenupdate set LogSetId = LogSetIdToUpdateTo


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4932626.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-13
下一篇2022-11-13

发表评论

登录后才能评论

评论列表(0条)

    保存