Solved

SQL Statement to Update Rows on Condition

Posted on 2013-12-09
4
241 Views
Last Modified: 2013-12-09
I have duplicate rows in a table. All column values are equal except one numeric column.
I need to set a column value for the lowest Col3 value in each group.

Col1         Col2           Col3             Col4

1808      AA      30175130          1   Set Col4 to 0 for the min Col3 value of the AA Group
1808      AA      30176132          1
4450      AAN      30175454          1   Set Col4 to 0 for the min value of the AAN Group
8384      AAN      30175787          1
8385      AAN      30175788          1
4450      AAN      30177864          1
8384      AAN      30178679          1
8385      AAN      30178680          1

How can this be done?

Thanks,
0
Comment
Question by:Dovberman
  • 3
4 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 total points
ID: 39706084
Give this a whirl... a JOIN on your_table (rename to suit your needs) and a subquery that gets the minimum value of Col3 based on the Col2 value.
UPDATE your_table
SET Col4 = 0
FROM your_table yt
   JOIN (SELECT Col2, Min(Col3) as Col3_min
            FROM your_table
            GROUP BY Col2) yt_min 
   ON yt.Col2 = yt_min.Col2 AND yt.Col3 = yt_min.Col3_min

Open in new window

0
 

Author Comment

by:Dovberman
ID: 39706234
Thank you,

I will try this later today and reply.
0
 

Author Comment

by:Dovberman
ID: 39706532
Works perfectly,

Thanks,
0
 

Author Closing Comment

by:Dovberman
ID: 39706534
Works perfectly,

Thanks,
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how the fundamental information of how to create a table.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now