如何将两个视图合并为一个视图以压缩我的数据?

How can I combine two views into one to condense my data?

我有两个 table,一个有球员的名字和赢得的比赛数量,一个有球员的名字和输掉的比赛数量。我想将它们组合起来以显示玩家姓名、# 场比赛获胜和# 场比赛失利 table

还希望能够通过将赢的游戏加到输的游戏中来显示玩过的游戏数量

table1

name g_won
a 2
b 4

table2

name g_lost
a 2
c 5

想要新的 table 到 return:

name g_won g_lost g_played
a 2 2 4
b 4 0 4
c 0 5 5

您可以通过合并每个 table 的左侧或右侧 outer-join 然后聚合来获得您想要的结果。您可以将其创建为 视图 以将其作为另一个 table.

引用
select name, 
    Sum(g_won) g_won, Sum(g_lost) g_lost, 
    Sum(g_won) + Sum(g_lost) g_played
from (
    select t1.name, g_won, 0 g_lost
    from t1
    left join t2 on t2.name=t1.name
    union
    select t2.name, 0 g_won, g_lost
    from t2
    left join t1 on t2.name=t1.name
)t
group by name;

DB<>Fiddle

您可以应用 UNION 操作,然后对每个 g_wong_lost 应用 select SUM

SELECT name,
       SUM(g_won)        AS g_won,
       SUM(g_lost)       AS g_lost, 
       SUM(g_won+g_lost) AS g_played
FROM (SELECT name,
             g_won,
             0 AS g_lost
      FROM table1
      UNION
      SELECT name,
             0 AS g_won,
             g_lost
      FROM table2            ) tab 
GROUP BY name

试试看 here.