SQL Updating column in new table with arithmetic f

2019-08-23 10:19发布

问题:

I have two tables:

part of Table1:

 id  |  per  |  va   | gp | minutes 
-----+-------+-------+----+---------
   1 | 11.87 |  14.5 | 69 |    16.1
   2 | 17.07 | 154.9 | 78 |    23.9
   3 |  4.30 |  -8.6 | 21 |     4.4
   4 |  5.68 | -42.2 | 52 |     9.3
   5 | 19.46 | 347.8 | 82 |    32.1
   6 | 18.26 | 125.3 | 47 |    23.3
   7 | 12.76 |  79.0 | 82 |    28.5
   8 |  9.19 |  -3.7 | 13 |    14.8
   9 | 21.15 |  10.7 | 10 |     6.8
  10 | 14.38 |  46.1 | 31 |    25.7

Table2:

 player |           prl           | position 
--------+-------------------------+----------
 1      |                         | 
 2      |                         | 
 3      |                         | 
 4      |                         | 

I'm trying to calculate prl by taking those columns in table 1 and doing per - ((67*va)/(gp*minutes)). I can of course calculate this outside of inserting it into the prl column but can't find a way to get it into prl. The closest I've gotten is by doing this:

update hwk2
set prl = per - ((67*va)/(gp*minutes)) from more_player_stats;
UPDATE 1904

which gives me the same result throughout the entire prl column. Can anyone help out this brand new sql user?

回答1:

Use an update join:

UPDATE hwk2 AS t1
SET prl = t1.per - ((67*t1.va) / (t1.gp*t1.minutes))
FROM more_player_stats AS t2
WHERE t1.player = t2.id;

Here is a link to a reference question on SO covering updates in Postgres.