Question

I am trying to use 4 queries and get one resulting table. I have tried UNIONs and JOINs and not been able to accomplish this. I would be extremely appreciative if someone here might know the solution. Below is the table I am operating on, the queries I am using, and the results I get.

-- TABLE

             Table "public.games"
  Column   |         Type          | Modifiers 
-----------+-----------------------+-----------
 gamedate  | date                  | not null
 hometeam  | character varying(50) | not null
 awayteam  | character varying(50) | not null
 homescore | character varying(50) | 
 awayscore | character varying(50) | 
Indexes:
    "date_teams" PRIMARY KEY, btree (gamedate, hometeam, awayteam)

-- QUERIES

-- Display teams and their total number of wins and losses

SELECT homeTeam, count(*) AS Wins
FROM games
WHERE homeScore > awayScore
GROUP BY homeTeam;

SELECT homeTeam, count(*) AS Losses
FROM games
WHERE homeScore < awayScore
GROUP BY homeTeam;

SELECT awayTeam, count(*) AS Wins
FROM games
WHERE homeScore < awayScore
GROUP BY awayTeam;

SELECT awayTeam, count(*) AS Losses
FROM games
WHERE homeScore > awayScore
GROUP BY awayTeam;

-- RESULTS

  hometeam  | wins 
------------+------
 Destroyers |    1
 Animals    |    2
 Powerpuff  |    1
 Madinights |    1
(4 rows)


 hometeam | losses 
----------+--------
 Aliens   |      1
 Animals  |      1
(2 rows)


 awayteam | wins 
----------+------
 Steel    |    1
 America  |    1
(2 rows)


 awayteam | losses 
----------+--------
 Knights  |      1
 Bengals  |      1
 Fairies  |      1
 Beakers  |      2
(4 rows)

How can I get these four tables into one, with the team name never repeated?

Something like this:

team | wins | losses

-----------+------+-----

Knights | 0 | 1

Animals | 2 | 1

One Table that summarizes the wins and losses of each team, 'home' and 'away' are not desired.

Was it helpful?

Solution

Try:

SELECT team,
       SUM( Wins ) As Wins,
       SUM( Losses ) As Losses
FROM (
   SELECT homeTeam As team, 
          SUM( case when homeScore > awayScore then 1 else 0 end ) AS Wins,
          SUM( case when homeScore < awayScore then 1 else 0 end ) AS Losses
   FROM games
   GROUP BY homeTeam
  UNION ALL
   SELECT awayTeam, 
          SUM( case when homeScore < awayScore then 1 else 0 end ) AS Wins,
          SUM( case when homeScore > awayScore then 1 else 0 end ) AS Losses
   FROM games  
   GROUP BY awayTeam
) q
GROUP BY team

demo: http://sqlfiddle.com/#!15/3db10/11


One remark:
you are using < and > operators in queries - this doesn't include cases when awayscore=homescore

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top