skip to Main Content

I have 2 tables made like so:

NickName Points
Player 1 15
Player 2 8
NickName Points
Player 1 33
Player 2 22

and I need to get this table:

NickName Points
Player 1 48
Player 2 30

Is it possible to do such thing using a single query in SQL?

2

Answers


  1. Join the two tables and perform an aggregation on the Points column using the UNION ALL

    SELECT NickName, SUM(Points) as Points
    FROM (
      SELECT NickName, Points FROM table1
      UNION ALL
      SELECT NickName, Points FROM table2
    ) as combined_tables
    GROUP BY NickName;
    

    db<>fiddle output

    Login or Signup to reply.
  2. The ideal design would be to have the data in the same table with a 3rd column defining whatever it is that currently separates your data (i.e. event/game etc). This would allow you to select the data either separately or aggregate.

    E.g.

    SELECT NickName, Points from mytable WHERE eventID = 1

    or

    SELECT NickName, SUM(Points) from mytable GROUP BY NickName

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search