Solved

# Update A Column based on results of another column

Posted on 2013-11-26
127 Views
In the same table "PropertyCalcs", I am try to update a column based a minimum value of another column.

I have PropertyID, OrderNumber, and First Inspection Date as columns.

For each ProptertyID, I need SQL to find the min(OrderNumber) and then write 'First Inspection Date' in the First Inspection Date column, when it finds the minimum OrderNumber for that PropertyID.

If you have any questions, please let me know and I'll be happy to answer them.
0
Question by:Erik Hauser

LVL 65

Accepted Solution

Jim Horn earned 500 total points
ID: 39678062
Air code.  I also do my own stunts..
``````UPDATE your_table
SET [First Inspection Date] = 'First Inspection Date'
FROM your_table yt
JOIN (
SELECT ProptertyID, min(OrderNumber) as min_order_number
FROM your_table
GROUP BY PropertyID) yt_min ON yt.PropertyID = yt_min.PropertyID AND yt.OrderNumber = yt_min.min_order_number
``````
0

Author Comment

ID: 39678085
JimHorn,

Thank you so much!  I was practically there in two separate queries and couldn't figure out how to join them.

Thanks, I'll try that!
0

LVL 50

Expert Comment

ID: 39678147
;with cte as (select [first inspection date]
,row_number() over ( partition by propertyid order by ordernumber) as rn
from propertycalcs)
update  x
set [first inspection date]='first inspection date'
from cte as x
where rn=1
and [first inspection date] <> 'first inspection date'
0

LVL 69

Expert Comment

ID: 39678594
I'd suggest storing just a bit flag that indicated this: you can translate it to the characters using a computed column.

isFirstInspectionDate bit

update ...
set isFirstInspectionDate = 1
...

ALTER TABLE PropertyCalcs
ADD [First Inspection Date] AS CASE WHEN isFirstInspectionDate = 1 THEN 'First Inspection Date' ELSE '' END
0

## Featured Post

### Suggested Solutions

In this article I will describe the Detach & Attach 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.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how the fundamental information of how to create a table.