select DepartmentName 部门,count(*) 人数 from TableA Group by DepartmentName

解决方案 »

  1.   

    谢谢大力!
    从mssql的帮助看到,count(distinct EmployeeID)似乎也可以的
    如果这个不对,问题出在哪里啊?
      

  2.   

    select count(Distinct EmployeeID) from TableA 
                                               Group by DepartmentName
    right!!!!
      

  3.   

    你没有必要Distinct你的EmployeeID不是主键吗?
      

  4.   

    count(*)这个速度并不比count(EmployeeID)慢哦~~`
      

  5.   

    count(*) 表示 计算所有行包括重复行,也包括空行(含null值的行)
    count(distinct colname) 表示统计colname列中不重复且不包含null值的行。
    对于你的表中employeeid 应该是主键,这两个没有区别,但个人认为,如此,count(*)要比
    count(distinct colname)快 ,因为后者要去重复值,前者不需要。
      

  6.   

    select count(Distinct EmployeeID) from TableA 
                                                  Group by DepartmentName
    这样写是不对的。因为在select 后面的字段必须都出现在group by 中。
    而group by 后的字段也改须都得在select 后出现!!!
      

  7.   

    to baby97() :我不同意你的观点,应该是在select子句中出现的字段必须在group by子句中
    出现,而在group by子句中出现的字段不一定非要在select 子句中出现!
      

  8.   

    如果在select子句中只有聚合函数如:sum,avg,count等,则在group子句中出现的字段不必在select子句中出现,
    而如果在select子句中出现了字段名,则group子句中出现的字段一定要在select子句中出现,注意,不是只包含在聚合函数中。
    如:
    use pubs
    go
    select count(*) from authors group by state              --没有出错,
    select state,au_lname,count(*) from authors group by state  --出错
    select state,au_lname,count(*) from authors group by state,au_lanme
    --没有出错