Combining duplicate records in SQL Server

ⅰ亾dé卋堺 提交于 2019-12-11 06:17:05

问题


I have a table in SQL Server 2012 that holds a list of parts, location of the parts and the quantity on hand. The problem I have is someone put a space in front of the location when they added it to the database. This allowed there to be two records.

I need to create a job that will find the parts with spaces before the location and add those parts to the identical parts without spaces in front of the location. I'm not quite sure where to even start with this.

This is the before:

  Partno  |  PartRev  |  Location  |  OnHand  |  Identity_Column
--------------------------------------------------------------------
  0D6591D    000          MV3         55.000     103939
  0D6591D    000         MV3          -55.000    104618

This is what I would like to have after the job ran:

  Partno  |  PartRev  |  Location  |  OnHand  |  Identity_Column
--------------------------------------------------------------------
  0D6591D    000         MV3         0           104618

回答1:


Two steps: 1. update the records with the correct locations, 2. delete the records with the wrong locations.

update mytable
set onhand = onhand + 
(
  select coalesce(sum(wrong.onhand), 0)
  from mytable wrong
  where wrong.location like ' %'
  and trim(wrong.location) = mytable.location
)
where location not like ' %';

delete from mytable where location like ' %';



回答2:


You can do some grouping with a HAVING clause on to identify the records. I've used REPLACE to replace spaces with empty strings in the location column, you could also use LTRIM and RTRIM:

CREATE TABLE #Sample
    (
      [Partno] VARCHAR(7) ,
      [PartRev] INT ,
      [Location] VARCHAR(5) ,
      [OnHand] INT ,
      [Identity_Column] INT
    );


INSERT INTO #Sample
    ([Partno], [PartRev], [Location], [OnHand], [Identity_Column])
VALUES
    ('0D6591D', 000, ' MV3', 55.000, 103939),
    ('0D6591D', 000, 'MV3', -55.000, 104618)
;

SELECT Partno ,
       PartRev ,
       REPLACE( Location, ' ', '') Location,
       SUM(OnHand) [OnHand]
FROM #Sample
GROUP BY REPLACE(Location, ' ', '') ,
         Partno ,
         PartRev
HAVING COUNT(Identity_Column) > 1;

DROP TABLE #Sample;

Produces:

Partno  PartRev Location    OnHand
0D6591D 0       MV3         0


来源:https://stackoverflow.com/questions/41984115/combining-duplicate-records-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!