【问题标题】:MySQL How to count and Sum condtionallyMySQL如何有条件地计数和求和
【发布时间】:2018-02-11 16:31:23
【问题描述】:

加入两个表后我得到MySQL的结果如下:-

        ID              ||    Category      ||       Cost       ||
========================||==================||==================|| 
AMWP/ABC/2016-17/1      ||      1           ||      123.88      ||
AMWP/CDF/2016-17/2      ||      2           ||      222.99      ||
AMWP/GHI/2016-17/3      ||      3           ||      133.90      ||
AMWP/ABC/2017-18/1      ||      1           ||      100.10      ||
AMWP/CDF/2017-18/2      ||      2           ||      200.20      ||
AMWP/GHI/2017-18/3      ||      3           ||      100.00      ||

我想根据类别和每个类别的计数和成本总和仅在 ID 具有类似于 ABC/CDF/GHI 之一和财政年度类似于 2016-17/2017-18 的条件下提取摘要

【问题讨论】:

    标签: mysql count sum conditional-statements


    【解决方案1】:

    我得到了我想要的方式。在以下 SQL 中,只要 Condition 为 True,我将使用 Sum 而不是 CountAdd 1 to TotWks。另外,只要条件为True,我只需Adding Cost FieldTotCost

    SELECT
    Category,
    SUM(if(ID LIKE '%2017-18%' AND ID like ‘%/ABC/%, 1, 0)) AS `TotWks`,
    SUM(if(ID LIKE '%2017-18%' AND ID like ‘%/ABC/%, `amwplist`.`Cost`, 0)) AS `TotCost`
    FROM  <main_Table>
    LEFT OUTER JOIN <join_Table> ON <main_Table.ID> = <join_Table. ID> 
    GROUP BY <main_Table.ID>
    

    如果我省略了GROUP BY 子句,那么我将在TotWksTotCost 下总计。

    感谢大家的帮助。

    【讨论】:

      【解决方案2】:
          select category, sum(Cost)
              from your_tables
              where 
              ( ID like ‘%/ABC/% or ID like ‘%/CDF%/’ or ID like ‘%/GHI/%’ )
              and 
              ( ID like ‘%/2016-17/%’ or ID like ‘%/2017-18/%’ )
              and <joining condition>
              group by category;
      

      【讨论】:

      • 先生,我的要求将满足`select category, sum(Cost) from your_tables where (ID like '%/ABC/%') and (ID like '%/2016-17/%')和 按类别分组;` 但 MySQL 在 and &lt;join&gt; 处抛出错误
      • by 条件我的意思是你用来连接2个表的条件。正如我从你的问题中了解到的那样,有一个加入。如果没有,请删除它。
      • 我明白你在说什么,但 MySQL 正在抛出错误。
      • 我们可以这样做SELECT category, SUM(CASE WHEN ID LIKE '%2017-18%' then Cost END) AS TotCost FROM your_tables WHERE (Category &lt;=3) GROUP BY ID
      • 抱歉耽搁了。错误是#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'JOIN'
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2011-12-22
      • 1970-01-01
      • 2022-01-04
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多