【问题标题】:sum two difrrent value from single table and subtract its value and group them by pcode将单个表中的两个不同值相加并减去其值并按 p 代码分组
【发布时间】:2013-09-12 10:07:11
【问题描述】:

我有 1 个名为 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  |

我的问题是,我想将备注 =“销售”的所有值求和,并将备注 =“返回”的所有值求和,然后在得到其总和后,我想将备注 =“销售”的总和减去总和其中备注 = 'return' 并按 pcode 分组。所以下面的输出一定是这样的。

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

我有这个 ff 代码,但它只能对备注 = '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 ");

【问题讨论】:

  • 如果可以,请检查您的餐桌设计。如果您的销售额为正数并返回负数,则计算会容易得多。在这种情况下,您可以进行简单的求和。我有一个与你的模式相似的数据库,获得正确的统计数据只是一场噩梦。

标签: php mysql


【解决方案1】:

您需要条件求和。假设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;

【讨论】:

    猜你喜欢
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多