Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select count from another table to each row in result rows

Here are the tables:

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

I want to get list of class, and each class - the number of student which belong to each class. How can I do this?

like image 613
Mosh Feu Avatar asked Jun 20 '12 05:06

Mosh Feu


People also ask

How do I count data from another table in SQL?

You can use Common Table Expression(Cte) to write such query with readability. ;With CteFamily AS ( SELECT family_id FROM dbo. Families --WHERE --Put your conditions to filter family ), --get childrens count, with family id for selected family CteChildrenCount AS ( SELECT family_id , Count(*) As ChildrenCount FROM dbo.

How do I join two tables and counts in SQL?

To achieve this for multiple tables, use the UNION ALL. select sum(variableName. aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName; Let us implement the above syntax.

How do I count rows from a select query?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.


2 Answers

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
like image 83
Kshitij Avatar answered Oct 11 '22 13:10

Kshitij


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]
like image 29
Kane Avatar answered Oct 11 '22 14:10

Kane