Link to home
Start Free TrialLog in
Avatar of Erik Hauser
Erik HauserFlag for United States of America

asked on

Update A Column based on results of another column

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.
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Erik Hauser

ASKER

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!
;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'
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