php - 使用 bool 值php计算mysql中的列总和

标签 php mysql checkbox sum

我有一个名为 expenses 的表,它包括以下几列:

ID, amount_1, amount_2, amount_1_paid, amount_2_paid, total

amount_x_paid 是一个 TINYINT,所以它用于复选框。

我想做的是根据amount_x_paid值(1,0)计算总数

让我们说:

amount_1 = 100
amount_2 = 200
amount_1_paid = 1
amount_2_paid = 0

这应该计算

 total = 100

如何在 php 中实现这一点?

php 文件将是一个计划任务作业,每天运行一次以计算总数。

这可以解决问题:

SELECT
 FORMAT(
   SUM(
     CASE
       WHEN amount_1_paid = 0 THEN (total + amount_1)
 ELSE (total - amount_1)
       END
    ),
    0
  )
AS total
  FROM
    expenses  
    WHERE ID = '1';

我怎样才能把它放在一个循环中并更新所有记录?

最佳答案

要根据 amount_x_paid 列选择 amount_ 字段,您可以使用 CASE 表达式。像这样:

SELECT
  CASE 
    WHEN amount_1_paid = 1 THEN amount_1 
    WHEN amount_2_paid = 1 THEN amount_2  
    ELSE 0
  END AS Amount,
  ...
FROM tablename;

如果您要查找这些金额的总和,请在子查询中使用它:

SELECT 
  SUM(Amount) AS Total,
  ...
FROM
(
    SELECT
      CASE 
        WHEN amount_1_paid = 1 THEN amount_1 
        WHEN amount_2_paid = 1 THEN amount_2  
        ELSE 0
      END AS Amount,
      ...
    FROM tablename
) AS sub;

关于php - 使用 bool 值php计算mysql中的列总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16058660/

相关文章:

javascript - 在没有提交按钮的情况下选中时如何获取复选框名称

php - Laravel 错误在 Debug模式下太误导以太了,有什么方法可以有更清晰的错误吗?

PHP 或 Linux Shell : Fastest way to reduce a text file that has more than 10 lines to only have the last 10 lines

php - Laravel 在使用 CASE WHEN 时如何使用 order by?

php - 使用自动建议 jQuery 插件的多标签

php - 使用变量,替换 SQL select 语句和 PHP Prepare 语句。我哪里出错了?

javascript - 如何将 localStorage 应用于输入复选框?

javascript - 在 li jquery 中选中复选框时获取输入文本值?

php - 如何使用 Reddit 和 Hacker News 排名算法?

mysql - 时间戳比较不适用于 TIMESTAMP 字段