例如,标记n = 4的连续重复项

时间:2018-01-18 18:58:42

标签: sql-server

此代码适用于标记所有项目,但只有在有定义的重复次数时,我才能使其适应。有什么想法吗?

UPDATE nl
    SET nl.description = (
        SELECT MAX(l.id2_location)
        FROM locations l 
        WHERE l.id_location = nl.id_location
    )
FROM newlocations nl
WHERE EXISTS (
    SELECT *
    FROM locations l
    WHERE l.id_location = nl.id_location
);

请参阅http://www.sqlfiddle.com/#!6/b8c33/16

1 个答案:

答案 0 :(得分:1)

按照您提供的小提琴,这是一个修改后的更新:

UPDATE nl set [description] = sq.Location2
FROM newlocations nl
  inner join (
    select l.id_location, max(l.id2_location) as [Location2]
    from locations l
    group by l.id_location
  ) sq on nl.id_location = sq.id_location
where exists (
  select 0 from newlocations c
  where c.id_location = nl.id_location
  group by c.id_location
  having count(*) >= 4
);

请注意,在您的示例数据中,没有id_location值重复4次,这就是我将>=置于过滤条件中的原因。