Select count from another table to each row in result rows

前端 未结 5 713
北恋
北恋 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:36

    You mean something like this?

    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]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-08 23:47
    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
    
    0 讨论(0)
  • 2021-02-08 23:48

    You need to do this -

    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
    
    0 讨论(0)
  • 2021-02-08 23:50
     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
    
    0 讨论(0)
提交回复
热议问题