SQL计数列和创建具有计算的表

时间:2014-02-24 22:13:16

标签: sql sql-server

我不确定如何正确地标出标题,所以如果它令人困惑,我道歉。

我需要做的是计算每个部门运行的项目数量,我需要显示每个部门名称并为计算结果分配一个名称

DEPARTMENT Table Imgur

PROJECT Table Imgur

这是我到目前为止所尝试的,但它返回一个错误:

    SELECT DISTINCT DepartmentName, COUNT(*) AS AmountOfProjects
    FROM DEPARTMENT, PROJECT;

2 个答案:

答案 0 :(得分:4)

SELECT DepartmentName, Count(1) AS AmountOfProjects
FROM Project
GROUP BY DepartmentName

您不需要Department表,因为Department的全名在项目表中。

你遗漏了Group By。只要您在select中有聚合函数,就需要Group By

答案 1 :(得分:0)

当我尝试使用user3083310解决方案仍然看起来有问题时,所有部门都显示了5个项目,这是错误的。我添加了以下连接,它起作用了:

    SELECT DEPARTMENT.DepartmentName, Count(*) AS AmountOfProjects
    FROM PROJECT, DEPARTMENT
    WHERE PROJECT.Department = DEPARTMENT.DepartmentName
    GROUP BY DEPARTMENT.DepartmentName;

输出如下,与项目表的信息相匹配。

部门名称:帐户财务营销

AmountOfProjects :1 - 2 - 2