使用where子句查找两列的差异 - MySQL

时间:2017-06-06 07:41:55

标签: mysql sql join inner-join difference

我正在尝试使用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

结果:

enter image description here

我想要做的是获得列(其他),其中type = 5和Column(Senior),其中seniortype = 10

这是我对高级的查询:

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

结果:

enter image description here

以下是我对其他的查询:

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

enter image description here

结果应为

9907 = 530
9912 = 63.71

任何人都可以帮我这个吗? :(

样本/预期输出:

enter image description here

3 个答案:

答案 0 :(得分:2)

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

您可能正在寻找以下内容,即每个ID的聚合,其中您分别对类型5和seniortype 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。如果你保留它并且值不能为null,那么你可以删除合并。)

答案 1 :(得分:0)

你可以尝试一下:

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`;

它只是加入了你的两个问题。

答案 2 :(得分:0)

请尝试此查询

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
相关问题