使用SQL

时间:2016-05-06 20:33:06

标签: mysql sql relational-database

我有一个由部门和收入栏组成的表格。表中有许多条目,每个条目都在某个部门并显示收入。我正在尝试使用MySQL来按部门查询收入的总和,并操纵结果。

例如,我想显示(部门A的收入总和)除以2,(部门B的收入的总和)和(部门C的收入的总和)除以4.

我设法找到每个部门总收入的总和:SELECT Department,SUM(Income) AS income FROM School GROUP BY Department;

但是我如何操纵总和以便我可以为每个部门划分不同的数字,并显示结果?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以使用CASE WHEN

SELECT Department ,
       SUM(case department when 'A' Income else 0 end)/2 AS income_A,
       SUM(case department when 'B' Income else 0 end)  AS income_B,
       SUM(case department when 'C' Income else 0 end)/4 AS income_C,
FROM School GROUP BY Department;

答案 1 :(得分:0)

您可以拥有一个名为 ModifiedIncome

的列
SELECT 
Department,
SUM(Income),
CASE 
WHEN Department = 'A' THEN SUM(Income) / 2
WHEN Department = 'B' THEN SUM(Income)
WHEN Department = 'C' THEN SUM(Income) / 4
END
 AS ModifiedIncome FROM School GROUP BY Department;