简体   繁体   中英

How to write a SQL query have multiple summed columns in the result table?

For example, there are 2 tables:

SERIES: with 3 relevant columns (2 teams are in a series): series_id, team1_id and team2_id

RESULTS: with 3 relevant columns: series_id, team_id (and time)

Each time a team wins a game of a SERIES, a row is inserted into the RESULTS table.

I must know the current score of each SERIES. So I'll need to join the tables on series_id and on team id. However i want a result that looks like this:

series team1 team2
------------------
1        4     3
2        3     1
3        2     4

I do not understand how to get multiple columns in the result table, both of which store SUMs of conditional rows from the input tables. Any ideas?

Join the tables on series_id , then group by series and count the number of times the winning team matches the respective participants in the series (in MySQL one can use SUM(boolean expression) to perform the count, since TRUE equates to 1 and FALSE to 0 ):

SELECT   series_id,
         SUM(RESULTS.team_id = SERIES.team1_id) AS team1,
         SUM(RESULTS.team_id = SERIES.team2_id) AS team2
FROM     SERIES LEFT JOIN RESULTS USING (series_id)
GROUP BY series_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM