CREATE TABLE #input (ID INT, B VARCHAR(10), C VARCHAR(15), D INT, [1] VARCHAR(15), [2] INT, [3] VARCHAR(15), [4] INT,[5] VARCHAR(15), [6] INT)
CREATE TABLE #output (ID INT, B VARCHAR(10), [1] VARCHAR(15), [2] INT, [3] VARCHAR(15), [4] INT, [5] VARCHAR(15), [6] INT)
INSERT INTO #input (ID,B,C,D)
VALUES (1,'Hat', 'Device1', 34 )
INSERT INTO #input (ID,B,C,D)
VALUES (2,'Mat', 'Device2', 65 )
INSERT INTO #input (ID,B,C,D)
VALUES (3,'Cat', 'Device3', 76 )
INSERT INTO #input (ID,B,C,D)
VALUES (3,'Sat', 'Device4', 34 )
INSERT INTO #input (ID,B,C,D)
VALUES (3,'Hat', 'Device5', 89 )
INSERT INTO #input (ID,B,C,D)
VALUES (4,'Hat', 'Device6', 76 )
INSERT INTO #input (ID,B,C,D)
VALUES (4,'Hat', 'Device7', 12 )
DECLARE
@id INT,
@b VARCHAR(10),
@c VARCHAR(15),
@d INT
DECLARE input CURSOR FOR SELECT ID, B, C, D FROM #input
OPEN input
FETCH NEXT FROM input INTO @id, @b, @c, @d
WHILE @@fetch_status <> -1
BEGIN
IF @id NOT IN (SELECT ID FROM #output)
BEGIN
INSERT INTO #output (ID,B,[1],[2])
VALUES (@id, @b, @c, @d )
END
ELSE IF @id IN (SELECT ID FROM #output) AND (SELECT [3] FROM #output WHERE ID = @id) IS NULL
BEGIN
UPDATE #output
SET [3] = @c,
[4] = @d
WHERE ID = @id
END
ELSE
BEGIN
UPDATE #output
SET [5] = @c,
[6] = @d
WHERE ID = @id
END
FETCH NEXT FROM input INTO @id, @b, @c, @d
END
CLOSE input
DEALLOCATE input
SELECT * FROM #input
SELECT * FROM #output
DROP TABLE #input
DROP TABLE #output
Вы можете попробовать это здесь:
https://dbfiddle.uk/?rdbms=sqlserver_2012&fiddle=bb3f59d0df1ddfdfba8d31c38b742919