Solved

SQL Statement to Update Rows on Condition

Posted on 2013-12-09
4
239 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
Comment Utility
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
Comment Utility
Thank you,

I will try this later today and reply.
0
 

Author Comment

by:Dovberman
Comment Utility
Works perfectly,

Thanks,
0
 

Author Closing Comment

by:Dovberman
Comment Utility
Works perfectly,

Thanks,
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

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.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

762 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

9 Experts available now in Live!

Get 1:1 Help Now