PSQL:将多个查询的结果组合/连接到一个表中

时间:2014-05-01 05:13:18

标签: postgresql join psql

我正在尝试使用4个查询并获得一个结果表。我尝试过UNIONs和JOINs,但是没能完成。如果有人在这里知道解决方案,我将非常感激。下面是我正在操作的表,我正在使用的查询以及我得到的结果。

- 表

             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)

- 查询

-- 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;

- 结果

  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)

如何将这四个表合并为一个,团队名称从不重复?

这样的事情:

  

团队|胜|损失

     

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

     

骑士| 0 | 1

     

动物| 2 | 1

一张表总结了每支球队的胜负,“主场”和“离开”是不可取的。

1 个答案:

答案 0 :(得分:0)

尝试:

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

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


一句话:您在查询中使用<>运算符 - 这不包括awayscore=homescore

时的情况
相关问题