Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to subtract the sum of a column from the column of another table

What I have tried:

SELECT requestformtbl.employee_name, requestformtbl.request_type, requestformtbl.total_day,
                requestformtbl.request_status, requestformtbl.admin_remark, requestformtbl.confirmed_by, requestformtbl.date_confirmed, requesttbl.max_allotment,
                (requesttbl.max_allotment - sum(requestformtbl.total_day)) as Available from requestformtbl inner join requesttbl on 
                requestformtbl.request_type = requesttbl.request_type;


error: Column 'requestformtbl.employee_name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.


Please help, thank you!
Posted
Updated 6-Dec-19 20:11pm
v3

1 solution

I don't know what others do but I do like this:

I have created two tables like this

create table if not exists table1(t1_col1 int);


create table if not exists table2(t2_col1 int);


and I have inserted four sample values in table1 like this,

insert into table1 values(1), (2), (3), (4);


and two sample values in table2 like this

insert into table2 values(1), (2);


Now lets see how to subtract the sum of col1 of table2 with every values in col1 of table1

select t1_col1 as original, (select sum(t2_col1) from table2) as sum, t1_col1-(select sum(t2_col1) from table2) as result from table1;


and I get result like this,

+----------+------+--------+
| original | sum  | result |
+----------+------+--------+
|        1 |    3 |     -2 |
|        2 |    3 |     -1 |
|        3 |    3 |      0 |
|        4 |    3 |      1 |
+----------+------+--------+




Or if you want to subtract sum with sum

select sum(t1_col1) - (select sum(t2_col1) from table2) as difference from table1;


which gives,

+------------+
| difference |
+------------+
|          7 |
+------------+
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900