php/mysql add rows together to get total

19,222

Solution 1

To add fields (columns):

SELECT col1, col2, col3, (col1+col2+col3) AS Total FROM table;

To add rows together, use the SUM() aggregate:

SELECT
  userid,
  SUM(col1) AS col1_total,
  SUM(col2) AS col2_total
FROM table
GROUP BY userid

Solution 2

You can add in your query string.

SELECT (field1 + field2) AS Total
FROM table
Share:
19,222
JonYork
Author by

JonYork

Updated on August 07, 2022

Comments

  • JonYork
    JonYork almost 2 years

    here's the scenario. I am generating a report of all the members who have dues to pay for a certain time period.

    I am successfully selecting and displaying each database entry as a row in a html table.

    The problem is the total fields the report must have. Each member pays different amounts based on what services they use, so I must add the values in each field individually to ensure proper result.

    Question is, how do I go about adding the rows/field together?

    Edit:

    To clarify. I am adding dues paid and donations paid fields. They are classified and integer in mysql database.

    Example, let's say that my query returns 3 results. I wish to add the dues paid for all 3 results and display it as total_dues_paid. Same idea for donations.

    This must be dynamic for any given number of results, as this changes month to month and we have seen several hundred results in some months.

    Thanks