从另一个表中选择计数到结果行中的每一行

时间:2012-06-20 05:59:51

标签: sql sql-server sql-server-2008 stored-procedures

以下是表格:

CREATE TABLE [dbo].[Classes](
    [ClassId] [int] NOT NULL,
    [ClassName] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Classes] PRIMARY KEY CLUSTERED 
(
    [ClassId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Students](
    [StudentId] [int] NOT NULL,
    [ClassId] [int] NOT NULL,
 CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED 
(
    [StudentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Students]  WITH CHECK ADD  CONSTRAINT [FK_Students_Classes] FOREIGN KEY([ClassId])
REFERENCES [dbo].[Classes] ([ClassId])
GO
ALTER TABLE [dbo].[Students] CHECK CONSTRAINT [FK_Students_Classes]
GO

我想获得课程列表,以及每个班级 - 每个班级的学生人数。 我怎么能这样做?

5 个答案:

答案 0 :(得分:18)

你需要这样做 -

SELECT C.ClassId, C.ClassName, count(S.StudentId) AS studentCount
FROM CLASSES C LEFT JOIN STUDENTS S ON (C.ClassId=S.ClassId)
GROUP BY C.ClassId, C.ClassName

答案 1 :(得分:2)

你的意思是这样的吗?

SELECT C.[ClassName], COUNT(*) AS 'Number of Students'
FROM [dbo].[Classes] AS C
    INNER JOIN [dbo].[Students] AS S ON S.[ClassId] = C.[ClassId]
GROUP BY C.[ClassName]

答案 2 :(得分:0)

SELECT class.ClassId, count(student .StudentId) AS studentCount
FROM dbo.CLASSES class LEFT JOIN dbo.STUDENTS student ON (class.ClassId=student.ClassId)
GROUP BY class.ClassId

答案 3 :(得分:0)

 select c.ClassId,C.ClassName,COUNT(*) [Number of students]
 from Classes C,Students S
 where c.ClassId=S.ClassId
 group by C.ClassId,C.ClassName

答案 4 :(得分:0)

无需添加group by子句,您可以执行以下操作:

创建一个函数以获取学生人数:

go
CREATE FUNCTION [dbo].GetStudentsCountByClass(@classId int) RETURNS INT
AS BEGIN
    declare @count as int

    select @count = count(*) from STUDENTS  
    where ClassId = @classId

    RETURN @count
END

然后在您的select语句中使用它

SELECT * , dbo.GetStudentsCountByClass(ClassId) AS StudentsCount
FROM Classes