【问题标题】:Finding difference of two columns with where clause - MySQL使用 where 子句查找两列的差异 - MySQL
【发布时间】:2017-06-06 07:41:54
【问题描述】:

我正在尝试使用 WHERE 子句以及它们的总和来获取两列(OTHER AND SENIOR)的差异。公式工作正常,但是,我没有得到我想要的结果。

我尝试使用 INNER JOIN 来做到这一点,不幸的是它不是我期望的结果

这是我的查询:

select a.ID as EMPLOYEE, 
sum(a.amount) as other,
sum(b.amount) as senior, 
(sum(a.amount) - sum(b.amount)) as result 
from gndsale a 
INNER join gndsale 
b ON a.ID= b.ID 
where a.TYPE = "5" and b.seniortype = "10" 
group by a.ID

结果:

我想要做的是获得 Column (Other) where type = 5 和 Column (Senior) where Seniortype = 10

这是我对高级的查询:

 select ID as EMPLOYEE, sum(amount) 
 from gndsale 
 where seniortype = "10" 
 group by ID

结果:

这是我对其他的查询:

select ID as employee, sum(amount) 
from gndsale 
where type = "5" 
group by ID

结果应该是

9907 = 530
9912 = 63.71

谁能帮我解决这个问题? :(

样本/预期输出:

【问题讨论】:

  • 您能否发布带有一些示例数据和预期结果的数据库架构?
  • 嗨 Bikash,说实话,给我的数据表没有组织,我的任务是使用示例 excel 报告查找结果。
  • 我的理解是你想得到othersenior的区别,其中type=5和seniortype=10。如果我弄错了,请解释一下。
  • 编辑您的问题并显示示例输入和输出。下面给出的两个答案都不符合您的期望,我的结论是您从未明确表达过您的期望。

标签: mysql sql join inner-join difference


【解决方案1】:

您为该栏选择了一个非常糟糕的名称。尽管名称为ID,但它并不是用于标识表中记录的ID。

您可能正在寻找类似以下的内容,即每个 ID 的聚合,您分别对类型 5 和高级类型 10 求和:

select 
  a.ID as employee, 
  coalesce(sum(case when type = 5 then amount end), 0) as other, 
  coalesce(sum(case when seniortype = 10 then amount end), 0) as senior, 
  coalesce(sum(case when type = 5 then amount end), 0) -
  coalesce(sum(case when seniortype = 10 then amount end), 0) as result
from gndsale
group by a.id
having sum(type = 5) > 0 and sum(seniortype = 10) > 0;

(HAVING 子句确保只获取同时具有 type = 5 和 Seniortype = 10 的记录的 ID。我们在这里使用 MySQL 的 true = 1 / false = 0。如果您还需要其他 ID,请将其删除。如果你保留它并且值不能为空,那么你可以删除合并。)

【讨论】:

  • 这得到了我正在寻找的结果!!!这花了我几个小时......谢谢Thorsten,如果我没有早点说清楚我的问题,我很抱歉......
【解决方案2】:

你可以试试这个:

SELECT 
    a.`employee`,
    sum(a.`amount`) - sum(b.`amount`) as total
FROM `gndsale` a
JOIN `gndsale` b
ON a.`employee` = b.`employee` and b.`senior_type` = "10"
WHERE a.`type` = "5"
GROUP BY a.`employee`
ORDER BY a.`employee`;

它只是连接你的两个查询。

【讨论】:

  • 对不起,它没有给我想要的结果:( 9907 = 1987.60 and 9912 = 20.47
【解决方案3】:

请试试这个查询

select employee, other, senior, (other-senior) AS result
From (
    select ID as employee,
           sum(if(type=5,amount,0)) AS other,
           sum(if(seniortype =10,amount,0)) AS senior 
           from gndsale group by ID
) a

【讨论】:

    猜你喜欢
    • 2020-01-10
    • 2012-09-02
    • 2020-01-22
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2011-07-13
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多