Hendry
Hendry

Reputation: 87

Add column values to eachother in PHP and MYSQLI

I've been trying to figure out how to count all column values and add them to each other.

Image

What i want to achieve is that my code will calculate all the price values, where check = 1 and add them to eachother as $total.

My goal : So i can divide the total result where check = 1, and check is 0, and subtract them from eachother.

I apologize for my paint skills.

Upvotes: 1

Views: 249

Answers (3)

lloiacono
lloiacono

Reputation: 5050

Try this:

SELECT sum(price) as Total from YOUR_TABLE where `check` = 1;

Upvotes: 2

amit rawat
amit rawat

Reputation: 783

You can try the following:

Step 1: Query all results from the table.
Step 2: Loop through the result.
Step 3: Create two array array1 and array2
Step 4: Inside the loop check condition if (check == 1) stored price value in array1 else if (check == 0) store in array2
Step 5: sum values of array1 and array2 in different variables and finally subtract from each other.

or try the following query:

 SELECT SUM(CASE WHEN check='0' THEN price END) as zerossum,
        SUM(CASE WHEN check='1' THEN price END) as onessum
  FROM tablename

Upvotes: 2

RiggsFolly
RiggsFolly

Reputation: 94662

You can get the complete answer using just SQL if you want

SELECT ones - zeros as theTotal
FROM
(
    SELECT SUM(CASE WHEN `check`=0 THEN price END) as zeros,
           SUM(CASE WHEN `check`=1 THEN price END) as ones
    FROM test
) test1;

Upvotes: 1

Related Questions