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.