如何在MS-SQL中对同一列的不同值使用Count函数?

时间:2015-09-24 15:50:25

标签: sql sql-server database sql-server-2008 sql-server-2005

对于数据库StudentInfo和表Student,如下所示:

CREATE TABLE Student
(
     ID INT PRIMARY KEY IDENTITY(1,1),
     Name nvarchar(255)
)

并插入值:

Insert Into Student Values ('Ashok')` 

执行3次,

Insert Into Student Values ('Achyut')

执行2次,总共5行数据插入表中。

我想显示一个计算结果的结果,其名称为'Ashok'& 'Achyut'。

通常,对于我使用的列中的单个值计数:

 SELECT Count(Name) AS NoOfStudentHavingNameAshok 
 FROM Student
 WHERE Name = 'Ashok'

但如何显示NoOfStudentHavingNameAshok& NoOfStudentHavingNameAchyut我应该运行什么查询?

2 个答案:

答案 0 :(得分:4)

您应该在nameselect group by中添加name

SELECT name, Count(*) 
From Student
group by name

答案 1 :(得分:3)

您可以在COUNT()函数中添加条件:

select count(case when Name = 'Ashok' then 'X' end) as NoOfStudentHavingNameAshok,
       count(case when Name = 'Achyut' then 'X' end) as NoOfStudentHavingNameAchyut
  from Student