简体   繁体   English

在表的另一列中查找具有某些字符串的列的总和

[英]Find sum of column with certain string(s) in another column in a table

I am trying to work on a project that needs to find the total sum and the total sum with a certain criteria. 我正在尝试一个项目,该项目需要找到总金额和具有一定条件的总金额。 Currently, I have managed to just calculate the total sum of column "price". 目前,我设法只计算了“价格”列的总和。 Here is the code: 这是代码:

$sumQuery = "SELECT SUM(price) AS value_sum FROM tickets";
//$dbc is Database Connection
$sumResponse = @mysqli_query($dbc, $sumQuery);
$sumRow = mysqli_fetch_array($sumResponse); 
$sum = $sumRow['value_sum'];

I want to work upon this code and make it be more specific. 我想研究这段代码,并使其更加具体。 Instead, I want it to ONLY calculate the sum of column "price" if in that row it has the string "Check" or "Cash" in the column "paytype". 相反,我希望它仅计算“价格”列的总和,前提是该行在“支付类型”列中包含字符串“检查”或“现金”。 I have no idea where to start with this. 我不知道从哪里开始。 I have done my research prior to asking this question, but came out with no results. 在问这个问题之前,我已经做过研究,但是没有结果。

Here is a snippet of my table which may help you understand more: 这是我的表格的一个片段,可以帮助您了解更多信息:

门票表

Here is a simple version of what I want to achieve if my description made no sense. 如果我的描述没有意义,这是我想要实现的目标的简单版本。 Find sum of column "price" for each row with the string "Check" or "Cash" in the column "paytype". 在“ paytype”列中为字符串“ Check”或“ Cash”找到每一行的“ price”列总和。

Use conditional aggregation: 使用条件聚合:

SELECT SUM(price) AS value_sum,
       SUM(CASE WHEN paytype IN ('Check', 'Cash') then price end) as check_or_cash
FROM tickets;

Of course, if you only want the sum for check/cash then you would use a WHERE clause. 当然,如果只希望支票/现金总和,则可以使用WHERE子句。

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

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