Select count from another table to each row in result rows

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

提交回复
热议问题