Solved

SQL Statement to Update Rows on Condition

Posted on 2013-12-09
4
247 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

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

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.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

830 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