I am trying to condense data in a database table which contains several instances of unique records with various column data.
I want to select the highest occurring value for each column for each particular unique record
But my SQL transaction is not working.
[dataBase1].[dbo].[table1]
has several hundred thousand records with several columns (Name, Place, etc.)
.
[dataBase1].[dbo].[table2]
has the list of unique Names from [table1]
and the headers for the rest of the columns (Place, etc.) which are empty.
I tried the following code.
DECLARE @name varchar(max);
DECLARE @place varchar(max);
DECLARE db_cursor SCROLL CURSOR FOR
SELECT [Name]
FROM [dataBase1].[dbo].[table2];
OPEN HostName_cursor
FETCH NEXT FROM db_cursor INTO @name;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT DISTINCT TOP(1) @place = [Place]
FROM [dataBase1].[dbo].[table1]
WHERE [Name] = @name
AND [Place] IS NOT NULL AND [Place] <> ''
AND (EXISTS (SELECT [Place], COUNT (*) AS TOTAL
FROM [dataBase1].[dbo].[table1]
GROUP BY [Place]))
GROUP BY [Place];
UPDATE [dataBase1].[dbo].[table2]
SET [Place] = @place
WHERE [Name] = @name;
SET @place = '';
FETCH NEXT FROM db_cursor INTO @name
END
[Place]
column for a particular unique [Name]
has 53 values and the highest repeating Value count is 3. In essence, I want automate the following SQL transaction for each unique [Name]
.
SELECT DISTINCT TOP 1
[Place], COUNT (*) TOTAL
FROM
[dataBase1].[dbo].[table1]
WHERE
[Name] = 'xxxxxx'
AND [Place] IS NOT NULL AND [Place] <> ''
GROUP BY [Place]
ORDER BY TOTAL DESC;