Related Tags:
SQL SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database. According to ANSI (American National Standards Institute), it is the standard language for relational database management systems. Learn More, SQL Server Management Studio (SSMS) SQL Server Management Studio (SSMS) is a software application first launched with Microsoft SQL Server 2005 that is used for configuring, managing, and administering all components within Microsoft SQL Server. Learn More, MSSQL Microsoft SQL Server is a relational database management system, or RDBMS, that supports a wide variety of transaction processing, business intelligence and analytics applications in corporate IT environments. It's one of the three market-leading database technologies, along with Oracle Database and IBM's DB2. Learn More,

In a many to many relationship, get records of table A associated with more than N number records of table B?

Description:I have Table A(assumed as Student) and Table B(assumed as Course) with their junction Table AB (StudentCourse),For example considering the following tables I need to get all the students with their Id and name who have enrolled in more than three(N) courses


|Student|
|Id |
|Name |



|Course|
|Id |
|Name |



|StudentCourse|
|Id |
|SId |
|CId |

Posted by: | Posted on: Apr 17, 2019

1 answers

Replies

3

You can get your desired result by simply joining the three tables and placing the required columns in the group by and having clauses as well as shown in the following query.

SELECT A.[Id],A.[Name],count(B.[Id]) as TotalEnrolledCourses FROM [Student] as A
inner join [StudentCourse] as AB on A.Id=AB.SId
inner join [Course] as B on AB.CId=B.Id
group by A.[Id],A.[Name] having count(B.[Id])>3

Replied by: | Replied on: Apr 17, 2019



Reply
×

Code block Hyperlink bold Quotes block Upload Images

Preview