By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,054 Members | 1,299 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,054 IT Pros & Developers. It's quick & easy.

Find sum of SUM columns from two mysql tables?

P: 1

So, I have two tables, exam1 and exam2 which looks like these:
Expand|Select|Wrap|Line Numbers
  1. sid       physics     chemistry       biology
  2. 3           80           60              40
Expand|Select|Wrap|Line Numbers
  1. sid        physics    chemistry       biology
  2. 3            40           50             70

I want to find the sum of items from both tables (exam1 and exam2), like this

table: total
Expand|Select|Wrap|Line Numbers
  1. sid         physics         chemistry       biology
  2. 3               120            110            110
I wont always have to find total of all courses (physics, chemistry, biology), sometimes I may want to find sum of only two, one of all three subjects, so this is really a variable.

Since I program from VB.NET, the list of courses to be totaled can be specified by a user at run time and is kept in a variable say, "courses", so sometimes courses= (physics,chemistry,biology) sometimes courses=(physics,chemistry) and so on.

How can I then find a total of courses that the user selects? (still total of courses in exam1+exam2 tables)

Oct 26 '16 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 1,039
This is a question about MySQL, and not about dotnet ;)

u need UNION, short example:
Expand|Select|Wrap|Line Numbers
This produces a result which has 1 and 2 in it.
The keyword ALL determines if duplicate should be kept or ignored.

In your case:
Expand|Select|Wrap|Line Numbers
  1. SELECT sum(physics),sum(chemistry) FROM (
  2.    SELECT * FROM exam1
  3.    UNION ALL
  4.    SELECT * FROM exam2 ) X
  5. GROUP BY X.sid;
Dec 17 '16 #2

Post your reply

Sign in to post your reply or Sign up for a free account.