'TSQL calculate the number of records
I have 3 tables with relationships sets between them. Everything works fine.
Table Producent:
ProducentID (PK, int)
ProducentName (nvarchar)
Table Produced:
ProducentID (PK, FK, int)
FilmID (PK, FK, int)
Table Film:
FilmID (PK, int)
FilmName (nvarchar)
Each producent produced various number of films.
I need to generate the following output:
ProducentName | NumberOfProducedFilms
For example:
ProducentName | NumberOfProducedFilms
-------------------------------------
Peter P. | 2
John J. | 4
Michael M. | 7
Edward E. | 3
Solution 1:[1]
You should use count and group by as follows
SELECT P.producentname,
Count(filmName) NumberOfProducedFilms
FROM producent P
JOIN produced PD
ON P.producentid = PD.producentid
JOIN film F
ON PD.filmid = F.filmid
GROUP BY P.producentname
Solution 2:[2]
Thank you @RF1991 for the hint!
This is the full answer:
SELECT P.ProducentName, COUNT(PD.FilmID) NumberOfProducedFilms FROM Producent P
JOIN Produced PD ON P.ProducentID = PD.ProducentID
JOIN Film F ON PD.FilmID = F.FilmID
GROUP BY P.ProducentName
ORDER BY P.ProducentName ASC
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RF1991 |
| Solution 2 | Velimir Radlova?ki |
