我有一个名为rsales的表。例如,我可以从我的表“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 |
我的问题是我想要将所有值加上remarks =“sales”并将所有值加上remarks =“return”的总和,然后在得到它的总和后我想减去总和,其中备注='sales'总和其中remarks ='return'并按pcode对它们进行分组。所以以下输出必须是这样的。
| total | discount | profit | p_code |
| 20 | 6 | 15 | 1234 |
| 10 | 5 | 5 | 3333 |
我有这个ff代码,但它只能对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 ");
答案 0 :(得分:2)
您需要条件求和。假设remarks
仅采用“sales”和“returns”的值,那么以下是一种相对简单的方法:
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;