Group By with count不起作用

时间:2015-07-31 15:12:58

标签: sql sql-server

我正在尝试使用group by with count函数,但这不起作用。

SELECT 
    projects.AgencyId,
    projects.ProgramId,
    count(projects.ProjStatusByMin) as status,
    projects.ProjStatusByMin 
from 
    projects 
where 
    projects.AgencyId=40 
group by 
    projects.ProjStatusByMin

上面的代码完全适用于MySQL,现在我希望在SQL Server中实现相同的功能。

Select 
    ProjStatusByMin,
    COUNT(ProjStatusByMin) [projstatus] 
from 
    Projects
where 
    AgencyId=40 
group by 
    ProjStatusByMin,AgencyId,ProjId

但是,如果我选择像波纹管代码那样的单个列,那么按工作分组

Select 
    ProjStatusByMin,
    COUNT(ProjStatusByMin) [projstatus] 
from 
    Projects
where 
    AgencyId=40 
group by 
    ProjStatusByMin

现在如何选择多列来实现分组?

2 个答案:

答案 0 :(得分:4)

您必须将所有列(count计数函数中的列除外)添加到group by子句中。

SELECT projects.AgencyId,projects.ProgramId,count(projects.ProjStatusByMin) as status,
projects.ProjStatusByMin 
from projects 
where projects.AgencyId=40 
group by projects.ProjStatusByMin, projects.AgencyId,projects.ProgramId

答案 1 :(得分:0)

在Sql Server中,您必须在group by子句中编写所有列名,您将在select语句中选择它。