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

How do I Use Count Function for different values of the same column in MS-SQL?

对于DBStudentInfo和TableStudent如下:

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行数据到table。

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

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

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

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

您应该在 selectgroup by name 中包含 name

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

您可以将条件放入 COUNT() 函数中:

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