简体   繁体   中英

SQL (Oracle) Updating multiple rows with calculated values (distance by Pythagorean theorem)

How do I update all rows with calculated data derived from the values in two other columns of the same record?

Here's the situation:

I have a table called customers . It had 4 columns - Customer_ID , Customer_Name , Coordinate_X and Coordinate_Y '. Since creating and filling the table with data I have added an empty 5th column called Distance

What I'd like to do is fill the Distance column with the calculated distances from (0,0) to the locations specified in the Coordinate_X and Coordinate_Y columns of each row. I figured I could use Pythagoras's theory - and the correct values come up when I use the query:

Select SQRT(Power(customers.coordinate_x,2) + Power(customers.coordinate_y,2)) from customers

I fiddled about trying to make a trigger - failed that through lack of experience. Then I tried to fill the column using queries - failed that too.

I've been trying things like this;

update customers set distance = (Select SQRT(Power(customers.coordinate_x,2) + Power(customers.coordinate_y,2)) from customers) 

Nothing's working - the best I'm getting is ORA-01427: single-row subquery returns more than one row

The query is simpler than what you are doing:

update customers
    set distance = SQRT(Power(coordinate_x, 2) + Power(coordinate_y, 2)) 

Gordon's answer is correct. However, for this particular example, it's better to use a virtual column and you won't have to update the distance after changing a customer's coordinates:

create table customers (
  customer_id number,
  customer_name varchar(255),
  coordinate_x number,
  coordinate_y number,
  distance  number generated always as (SQRT(Power(coordinate_x, 2) + Power(coordinate_y, 2))) VIRTUAL

);

See this sqlfiddle: http://sqlfiddle.com/#!4/c6db3/4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM