1

I am new to SQL and I want to write a query to add multiple rows in a table.

For example:

Table:

matchid|player1id|player2id|player1score|player2score
101    |20       |10       |0           |100
101    |20       |10       |0           |100
101    |20       |10       |0           |100
201    |20       |10       |645         |0
201    |20       |10       |100         |700
201    |20       |10       |0           |100

Required output:

matchid|player1id|player2id|player1score|player2score
101    |20       |10       |0           |300
201    |20       |10       |745         |800

Note: I have to do this without using GROUP BY

4
  • SELECT matchid, player1id, player2id, player1score = SUM(player1score), player2score = SUM(player2score) FROM yourTable GROUP BY matchid, player1id, player2id Commented Dec 3, 2015 at 5:27
  • 4
    Why don't you want to use GROUP BY? Commented Dec 3, 2015 at 5:42
  • because its a costly operation Commented Dec 3, 2015 at 5:47
  • The alternatives are worse. Commented Dec 3, 2015 at 5:48

4 Answers 4

1

Without using GROUP BY:

SELECT *
FROM (
    SELECT DISTINCT matchid, player1id, player2id FROM tbl
) AS t
CROSS APPLY(
    SELECT
        SUM(player1score), SUM(player2score)
    FROM tbl
    WHERE
        matchid = t.matchid
        AND player1id = t.player1id
        AND player2id = t.player2id
) AS x(player1score, player2score) 
Sign up to request clarification or add additional context in comments.

Comments

1
  select matchid,player1id,player2id,SUM(player1score) as 
player1score,SUM(player2score) as player2score 
FROM table1
Group by player1id,player2id, matchid

1 Comment

thanks for the response tshoemake. Sorry, I forgot to mention that i dont want to use group by clause.
1
SELECT
    matchid, player1is, player2id,
    SUM(player1score) as player1score,
    SUM(player2score) as player2score 
FROM 
    tablename 
GROUP BY
    matchid, player1id, player2id

1 Comment

thanks for the response kaushik. Sorry, I forgot to mention that i dont want to use group by clause.
0

Does this satisfy the requirement?:

select
    matchid, player1id, player2id,
    (select sum(player1score from Table t2 where t2.matchid = t.matchid) as player1score,
    (select sum(player2score from Table t2 where t2.matchid = t.matchid) as player2score
from
    (select distinct matchid, player1id, player2id from Table) t

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.