douya7309 2016-09-13 02:59
浏览 69
已采纳

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

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:

Tickets Table

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".

  • 写回答

1条回答 默认 最新

  • douyazi1129 2016-09-13 03:01
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题