简体   繁体   中英

How to add n number of columns to an existing table,the new columns should have the aggregate of an existing column

I have a table like:

ID NAME SALARY
1  JOSE 100
2  KEVI 100
3  JAMS 200
4  SANJ 400

I need to get the output like:

ID NAME SALARY SALARY-1 SALARY-2 SALARY-3 SALARY-4 
1  JOSE  100   99       98       97       96
2  KEVI  100   99       98       97       96
3  JAMS  200   199      198      197      196
4  SANJ  400   399      398      397      396

How can I get the desired table?

If you just want output, then use a query:

select id, name, salary, salary-1, salary-2, salary-3, salary-4
from table t;

If you actually want to add these columns to the table, you can use alter table add column and then update the values.

Use this stored procedure to get your result. This is working for me. Please change the table and column name as per your db.

DELIMITER $$
DROP PROCEDURE IF EXISTS my_proc$$

CREATE PROCEDURE my_proc(n INT)
proc : BEGIN

SET @q = CONCAT('SELECT ID, NAME, SALARY');
SET @num = 1;

select_loop : LOOP

    SET @q = CONCAT(@q, ', SALARY - ',@num);

    IF n = 0 THEN
        LEAVE select_loop;
    END IF;

    SET n = n - 1;
    SET @num = @num + 1;

END LOOP;

SET @q = CONCAT(@q, ' FROM sal');

PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END$$

DELIMITER ;

Call the stored procedure with the number of salary columns you want in output

mysql> CALL my_proc(4);
+----+------+--------+------------+------------+------------+------------+------------+
| ID | NAME | SALARY | SALARY - 1 | SALARY - 2 | SALARY - 3 | SALARY - 4 | SALARY - 5 |
+----+------+--------+------------+------------+------------+------------+------------+
|  1 | jose |    100 |         99 |         98 |         97 |         96 |         95 |
|  2 | kevi |    100 |         99 |         98 |         97 |         96 |         95 |
|  3 | jams |    200 |        199 |        198 |        197 |        196 |        195 |
|  4 | sanj |    400 |        399 |        398 |        397 |        396 |        395 |
+----+------+--------+------------+------------+------------+------------+------------+
4 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

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