栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

合并查询返回ORA

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

合并查询返回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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380557.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号