计算百分比二值和求和算术运算mysql

时间:2018-10-05 07:01:26

标签: mysql sql

这是我桌子上非常基本的外观。我有第4列。

| Product_Id       | TypePayment_Id      | Value        | Percent      |
| ---------------- |:-------------------:| ------:      | ------------:|
| 25               | 1                   |  30          |  50.00       |
| 26               | 1                   |  40          |  25.00       |
| 27               | 1                   |  50          |  25.00       |
| 28               | 2                   |  25          |  50.00       |
| 29               | 2                   |  30          |  25.00       |
| 30               | 3                   |  85          |  50.00       |
| 31               | 3                   |  90          |  25.00       |
| 32               | 3                   |  100         |  25.00       |

需要生成此结果:

| TypePayment_Id      | Total        | Comission    |
|:-------------------:| ------:      | ------------:|
| 1                   |  120         |  37.50       |
| 2                   |  55          |  20.00       |
| 3                   |  275         |  90.00       |

我需要通过MYSQL查询生成此结果,这可能吗?

3 个答案:

答案 0 :(得分:0)

选择

TypePayment_Id

SUM({Value)AS Total

SUM(Value * Percent / 100)为Commission

your_table

TypePayment_Id

此代码有效。请检查。

示例:对于第一行

TypePayment_Id:1
总计:(30 + 40 + 50)= 120
佣金:总和((30 * 50)/ 100 +(40 * 25)/ 100 +(50 * 25)/ 100)= 37.5

答案 1 :(得分:-1)

尝试聚合

   select TypePayment_Id,sum(Value) as total, 
   (sum(Value)*max(Percent))/100.0 as commission
   from tablename
   group by TypePayment_Id

答案 2 :(得分:-1)

  • 使用SUM()之类的聚合函数。
  • Group By上进行TypePayment_Id
  • 从逻辑上讲,您需要每行计算佣金值;因为佣金百分比可能有所不同。然后,对它们进行求和,以计算为TypePayment_Id支付的总佣金。

尝试(对于MySQL)

SELECT  
  `TypePayment_Id`, 
  SUM(`Value`) AS `Total`, 
  SUM(`Value` * `Percent` / 100) As `Commission`
FROM `your_table` 
GROUP BY 
  `TypePayment_Id`