php/ mysql

i have 1 table named rsales. and let say for example i have this following values from my table "rsales"

id | total | discount |  profit | remarks | p_code |
 1 |  20   |   2      |    5    |  sales  |  1234  |
 2 |  20   |   4      |   10    |  sales  |  1234  |
 3 |  20   |   6      |   15    |  sales  |  1234  | 
 5 |  20   |   2      |    5    |  return |  1234  |
 6 |  20   |   4      |   10    |  return |  1234  |
 7 |  10   |   5      |    5    |  sales  |  3333  |
 8 |  10   |   5      |    5    |  sales  |  3333  |
 9 |  10   |   5      |    5    |  sales  |  3333  |
10 |  10   |   5      |    5    |  return |  3333  |
11 |  10   |   5      |    5    |  return |  3333  |

my problem is that i want to sum all values where remarks = "sales" and sum all values where remarks = "return" and then after getting its sum i want to subtract total sum where remarks = 'sales' to total sum where remarks = 'return' and group them by pcode. so the following output must be something like this.

 | total | discount |  profit |  p_code |
 |  20   |   6      |   15    |   1234  |
 |  10   |   5      |   5     |   3333  |

i have this ff code but it can only sum values where remarks = 'return'

$result1 = mysql_query ("SELECT sum(total)  as tot,sum(discount) as dis, sum(profit) as prof   FROM rsales WHERE remarks ='return' GROUP by p_code ");

You need conditional summation. Assuming that remarks only takes on the values of "sales" and "returns", then the following is a relatively simple way to do this:

SELECT sum(case when remarks = 'sales' then total else - total end) as tot,
       sum(case when remarks = 'sales' then discount else - discount end) as discount,
       sum(case when remarks = 'sales' then profit else - profit end) as profit,
       p_code 
FROM rsales
GROUP by p_code;

暂无
暂无

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question sum two different table and the subtract its total MYSQL - SUM VALUE TWO TABLE Insert trigger subtract value from another table Subtract a SUM value from a regular number to get a total in using PHP mysql query select distinct value from two table with the count of sum value in two table Find Same Array value from one single array and merge its value into new array group wise Randomly sum values, add/subtract them up, until you have a value match php Group and sum items from one table based on column value from another table How to subtract a value from one table while adding to another table? subtract from two different table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM