Select count from another table to each row in result rows

前端 未结 5 725
北恋
北恋 2021-02-08 23:15

Here are the tables:

CREATE TABLE [dbo].[Classes](
    [ClassId] [int] NOT NULL,
    [ClassName] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Classes] PRIMARY KEY CL         


        
5条回答
  •  無奈伤痛
    2021-02-08 23:42

    Without having to add the group by clause, you can do the following:

    Create a function to get the students count:

    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
    

    then use it in your select statement

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

提交回复
热议问题