Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a table named "Table1"
Its schema with data is like this

Id | col2 | col3 | col4 | col5 | isUnique | dbUnique
1 | red | 3M | 1995 | UK | 1 | null
2 | red | 3M | 1995 | UK | 0 | null
2 | red | 3M | 1995 | UK | 0 | null
3 | red | 3M | 1995 | UK | 0 | null
4 | pink | A4 | 2002 | USA | 1 | null
5 | pink | A4 | 2002 | USA | 0 | null

Now my question is that, that i want to update dbUnique column of this table, such that dbUnique should contain Id of Table1 where isUnique is 1 in all duplicate rows based on col2,col3,col4 & col5

So my updated data will look like this

Id | col2 | col3 | col4 | col5 | isUnique | dbUnique
1 | red | 3M | 1995 | UK | 1 | 1
2 | red | 3M | 1995 | UK | 0 | 1
2 | red | 3M | 1995 | UK | 0 | 1
3 | red | 3M | 1995 | UK | 0 | 1
4 | pink | A4 | 2002 | USA | 1 | 4
5 | pink | A4 | 2002 | USA | 0 | 4

this table has over 50,000 rows.

How can i do this in MS SQL 2008
Posted

1 solution

If Id is unique value, like this:
MIDL
Id | col2 | col3 | col4 | col5 | isUnique | dbUnique
1 | red | 3M | 1995 | UK | 1 | null
2 | red | 3M | 1995 | UK | 0 | null
3 | red | 3M | 1995 | UK | 0 | null
4 | red | 3M | 1995 | UK | 0 | null
5 | pink | A4 | 2002 | USA | 1 | null
6 | pink | A4 | 2002 | USA | 0 | null

(not: 1, 2, 2, 3, 4, 5) the fallowing instruction:
SQL
SELECT col2, Count(col2) AS CountOfCol2, Min(ID) AS MinOfID
FROM Table1
GROUP BY col2
HAVING (Count(col2)>1);

returns:
col2 | CountOfCol2 | MinOfID<br />
pink | 2 | 5<br />
red | 4 | 1<br />

So you need to build another instructions to update your table using data returned by previous instruction.
I'm not sure which column is grouping column, so i can't help you more.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900