
如果您看到我在两个查询中都使用了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
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)