简体   繁体   English

使用SQL查询总和

[英]Querying the sum using SQL

I have a table consisting of a department and income column. 我有一个由部门和收入栏组成的表格。 There are many entries in the table, each in a certain department and showing the income. 表中有许多条目,每个条目都在某个部门并显示收入。 I am trying to use MySQL to query the total SUM of income by department, and manipulating the results. 我正在尝试使用MySQL来按部门查询收入的总和,并操纵结果。

For instance, I want to show the (SUM of income of department A)divided by 2, (SUM of income of department B), and (SUM of income of department C)divided by 4. 例如,我想表示(部门A的收入的总和)除以2,(部门B的收入的总和)和(部门C的收入的总和)除以4。

I managed to find the sum of the total income of each department: SELECT Department,SUM(Income) AS income FROM School GROUP BY Department; 我设法找到每个部门的总收入总和: SELECT Department,SUM(Income) AS income FROM School GROUP BY Department;

But how can I manipulate the sums so that I can divide by a different number for each department, and show the results? 但是我如何操纵总和以便我可以为每个部门划分不同的数字,并显示结果? Any help would be appreciated. 任何帮助,将不胜感激。

You can use a CASE WHEN 您可以使用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;

You can have one column called ModifiedIncome 您可以拥有一个名为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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM