合并来自不同表的列

时间:2013-11-17 06:57:30

标签: sql database oracle

我有两个单独的select语句,它们都返回类似的信息

SELECT PlayerName, SUM(Field1) + SUM(Field2) AS Power
FROM (SELECT PlayerName, Field1, Field2
    FROM Plays INNER JOIN Creep ON Plays.Id = Creep.Id
    ) tmp 
GROUP BY PlayerName

返回

-- PlayerName         |Power       
-- ----------------------------
-- Player1            |4         
-- Player2            |5         

我有一个单独的电话

SELECT PlayerName, SUM(Field3) AS Weakness
FROM (SELECT PlayerName, Field3
    FROM Plays INNER JOIN WeakCreep ON Plays.Id = WeakCreep.Id
    ) tmp2
GROUP BY PlayerName

返回类似的结果

-- PlayerName         |Weakness      
-- ----------------------------
-- Player1            |1         
-- Player2            |3

我正试图找到一种生产方式

-- PlayerName         |Power        |Weakness     
-- ---------------------------------------
-- Player1            |4            |1      
-- Player2            |5            |3

感觉我已经尝试了JOIN和UNION的每个变体,但我找不到生成合并结果的方法。有关如何组合2个查询的任何建议吗?

2 个答案:

答案 0 :(得分:0)

尝试使用左连接

SELECT  p.PlayerName, 
    SUM(c.Field1) + SUM(c.Field2) AS Power , 
    SUM(w.Field3) AS Weakness   
FROM    Plays p , Creep c , WeakCreep w
where   p.Id = c.Id(+)
and p.Id = w.Id(+)
group by p.PlayerName

答案 1 :(得分:0)

尝试此查询:

SELECT PlayerName, SUM(Field1) + SUM(Field2) AS Power, SUM(Field3) AS Weakness
FROM(SELECT t1.PlayerName, t2.Field1, t2.Field2, t3.Field3
     FROM 
     Plays t1,Creep t2,WeakCreep t3
     where 
     t1.Id = t2.Id and t1.Id = t3.Id
     GROUP BY t1.PlayerName, t2.Field1, t2.Field2, t3.Field3)
     GROUP BY PlayerName;