I
I
IlyaPrivolnov3332022-02-16 13:24:32
SQL
IlyaPrivolnov333, 2022-02-16 13:24:32

How to add an amount from another table to an empty column of a table according to a given condition?

Suppose I have the following table:

column_1 | column_2 | column_3
__________ |___________ |__________
1 | 12 |
1 | 32 |
2 | 10 |
2 | 5 |
3 | 6 |
3 | 10 |

Please tell me what function should be written so that the sum from column_2 is calculated in column_3, taking into account the grouping with column_1? The final table should look like this:

column_1 | column_2 | column_3
__________ |___________ |__________
1 | 12 | 44
1 | 32 | 44
2 | 10 | 15
2 | 5 | 15
3 | 6 | 16
3 | 10 | sixteen

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexey, 2016-03-02
@ZmeuSnake

select 
 M.имя_маршрута
,G.имя_города 
,G2.имя_города
from Маршруты M 
inner join Города G ON  M.id_пункта_отправления=G.ID
inner join Города G2  ON  M.id_пункта_назначения=G2.ID

M
Michael, 2022-02-16
@Akela_wolf

Automatically update the table - it needs a trigger.
You can make a view (VIEW) and then, when requesting data from this view, the amount you need will be automatically calculated each time.

create table tbl (
        сol1 int,
  	col2 int
);

insert into tbl (col1, col2) values (1, 12), (1, 32), (2, 10), (2, 5), (3, 6), (3, 10);

CREATE VIEW tbl_sum AS SELECT tbl.*, SUM(tbl.col2) OVER (PARTITION BY tbl.col1) AS col3 FROM tbl;

SELECT * FROM tbl_sum;

https://sqlize.online/sql/mysql80/5b3c3e5b21a1083d...

S
Slava Rozhnev, 2022-02-16
@rozhnev

update tbl
join (
  select col1, sum(col2) col2_sum from tbl group by col1
) summed on summed.col1 = tbl.col1
set col3 = col2_sum;

MySQL online query

A
Akina, 2022-02-16
@Akina

Can you please tell me what function should be written so that the sum from column_2 is calculated in column_3, taking into account the grouping with column_1?

Before asking "how", justify why to do it.
Storing the aggregated sum in a table is called "overridden data". Which (1) is almost never necessary (2) is often just harmful. That's right - to read the required value from the source data at the moment when it is really needed.
Storing overridden data is just storing superfluous data. But this is not the only danger. Any abnormal situation - and the value can easily not be updated, or incorrectly updated. The result will be the storage of incorrect values ​​​​in the table. And what is most disgusting - this irregularity is not detected in any way. Until, finally, the use of an incorrect value backfires somewhere else, with fireworks and screams, or even with the dismissal of a programmer who allowed such an architectural jamb.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question