简体   繁体   中英

Merging columns from separate tables

I have 2 separate select statements that both return similar information

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

Which returns

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

I have a separate call

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

Which returns a similar result

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

I am trying to find a way to produce

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

It feels like I've tried every variation of JOIN and UNION but I cannot find a way to produce the combine results. Any suggestions as to how to combine the 2 queries?

Try using left joins

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

try this query:

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;

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