I have one table in MySQL database (just example)
CREATE TABLE test.Names (
id INT NOT NULL ,
salary INT NULL ,
name VARCHAR(45) NULL ,
tmpl INT,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC)
);
I have these records
id, salary, name, tmpl
1, 10, John, null
2, 20, Pat, null
3, 30, Jane, null
I’d like update the table by this simple calculation for each person
salary of each person/Sum(salary)*100
So the result should be
id, salary, name, tmpl
1, 10, John, 16.67
2, 20, Pat, 33.33
3, 30, Jane, 50
How to perform this by one SQL query? Or what is the best approach (I assume the real table will have >100 000 rows)
Use a separate SELECT statement to get the total salary – either put that in a variable, or cross-join this with your existing table. Then you have the sum available for each individual record.
This SQL code suffices:
No need for a join, even. Simpler this way and probably faster.