如何停止循环并添加值?

时间:2017-08-21 17:26:23

标签: php mysql loops sum case

我有下表:

id   tax    rate   quantity
 1   20     400       5
 2   20     566       2
 3   5      200       4

这是我的预期输出:

 taxableamount   taxamount      total
    3132.00        626.40      3758.40
     800.00         40.00       840.00

让我在这里解释一下我的尝试:

如果每一行具有相同的税额,我计算了每行数据的金额(rate × quantity),然后计算税额(amount × tax ÷ 100)并将结果显示在一行中,即使它们是来自多行。但如果行没有相同的税值,它将显示在单独的行中。

$query = "SELECT SUM(
          CASE WHEN tax=tax
          THEN rate*quantity ELSE 0 END) AS taxableamount,
          SUM(CASE WHEN tax=tax 
          THEN (rate*quantity)+(rate*quantity)*tax/100 ELSE 0 END) AS tax,
          SUM(CASE WHEN tax=tax 
          THEN (rate*quantity)*tax/100 ELSE 0 END) AS taxamount,
          SUM(CASE WHEN tax=tax 
          THEN (rate*quantity)+(rate*quantity)*tax/100 ELSE 0 END) AS total
          FROM pricing group by tax";
while($row = show($query)):
   echo '<td>'.$row->taxableamount.'</td>';
   echo '<td>'.$row->taxamount.'</td>';
   echo '<td>'.$row->total.'</td>';
endwhile;

上面的代码给了我错误和意想不到的结果。所以看看我的预期输出,我该怎么做呢。请帮忙。

2 个答案:

答案 0 :(得分:5)

您应该删除CASE语句。正如我在评论中所说,税收总是等于税收,因为你正在与同一行进行比较。我添加了税栏,因此您知道每种税的金额:

SELECT 
    SUM(rate * quantity) AS taxableamount,
    SUM(rate * quantity * tax / 100) AS taxamount,
    SUM(rate * quantity * (1 + tax) / 100) AS total,
    tax
FROM 
    pricing 
GROUP BY
    tax

答案 1 :(得分:0)

你要找的是你的sql语句中的group by tax。删除删除案例时。 col两行给col叫“税”?这对我来说就像是一个错误。

group by

aggregation