简体   繁体   English

将单个表中的两个不同值相加并减去其值并按pcode对它们进行分组

[英]sum two difrrent value from single table and subtract its value and group them by pcode

i have 1 table named rsales. 我有一个名为rsales的表。 and let say for example i have this following values from my table "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  |

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. 我的问题是,我希望将所有值汇总为remarks =“sales”并将所有值汇总到remarks =“return”,然后在得到它的总和后,我想减去总额,其中备注='sales'总额,其中备注= 'return'并按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' 我有这个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 ");

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: 假设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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM