Search code examples
sqlcountsubquerydb2-express-c

How to select attribute from joined tables with aggregate function?


These are three sample tables

Team

+-------------+-------------+
| TeamID      | TeamName    |             
+-------------+-------------+
| 11          | AA          | 
+-------------+-------------+
| 12          | BB          | 
+-------------+-------------+
| 13          | CC          |
+-------------+-------------+

Match

+-------------+
| MatchID     |        
+-------------+
| 1           |
+-------------+
| 2           | 
+-------------+
| 3           | 
+-------------+

Teammatch

+-------------+-------------+-------------+
| TmID        | Team_ID     |  MatchID    |
+-------------+-------------+-------------+
| 21          | 11          | 1           |
+-------------+-------------+-------------+
| 22          | 11          | 2           |
+-------------+-------------+-------------+
| 23          | 12          | 1           |
+-------------+-------------+-------------+
| 24          | 13          | 2           |
+-------------+-------------+-------------+
| 24          | 11          | 3           |
+-------------+-------------+-------------+

The goal is to list the TeamName where they attend the matches more than one time like below:

+-------------+
| TeamName    |             
+-------------+
| AA          | 
+-------------+

This is what I have tried:

SELECT TeamName 
FROM  Team T, Match M, Teammatch TM
WHERE T.TeamID = TM.TeamID AND
M.MatchID = TM.MatchID
......

But I really cannot figure out what to do next.

I have asked a similar question using SELECT COUNT before, but I do not really understand how to write the subquery here.


Solution

  • Try

        SELECT TeamName 
        FROM  Team T 
        JOIN  Teammatch TM ON T.TeamID = TM.TeamID
        JOIN  Match M ON M.MatchID = TM.MatchID
        GROUP BY TeamName
        HAVING COUNT(*) > 1
    

    Of course you could replace COUNT(*) with COUNT(DISTINCT M.MatchID) or similar.