-1

How to run query in php for sum of two or more column in horizintally.

suppose i have table like

srno   name   english  maths  science  TotalMarks
1      rohit  52       52     52           ?

so how to get sum of all marks. and show in total marks field. by php code.

3
  • 1
    You should normalize your database schema. Commented Dec 13, 2019 at 9:43
  • 1
    Just: select t.*, english + maths + science total_marks from mytable t? Commented Dec 13, 2019 at 9:44
  • Yep, that's not a table; it's a spreadsheet. :-( Commented Dec 13, 2019 at 10:01

4 Answers 4

1

The correct approach would be somewhat as follows:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,srno INT NOT NULL
,subject VARCHAR(20) NOT NULL
,mark INT NOT NULL
);

INSERT INTO my_table VALUES
(1,1,'english',52),
(2,1,'maths',52),
(3,1,'science',52);

SELECT srno
     , SUM(mark) total 
  FROM my_table
 GROUP 
    BY srno;
    +------+-------+
    | srno | total |
    +------+-------+
    |    1 |   156 |
    +------+-------+
Sign up to request clarification or add additional context in comments.

Comments

0

Try something like this:

SELECT srno, name, english, maths, science, (english+maths+science) As TotalMarks FROM `table_name`

Check also this topic: How to SUM two fields within an SQL query

Comments

0

Well You can try these two methods:

select * from Your_Table_Name;

and when you display your result, you can add all these values like:

srno   name   english  maths  science  TotalMarks
$id    $name  $english $maths $science ($english+$maths+$science)

OR

select id, name, english, math, science, (english+maths+science) as Total from Your_Table_Name;

Comments

0

Try this :

SELECT *, (english + maths + science) AS Total FROM table;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.