Click here to Skip to main content
15,887,812 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello
I need help with summing all values for a specific name in table.

table:

CREATE TABLE Games
(
    id INTEGER PRIMARY KEY,
    teamA TEXT,
    teamB TEXT,
    scoreA INTEGER,
    scoreB INTEGER )};


Insert:

INSERT INTO Games
    (teamA,teamB,scoreA,scoreB)
    VALUES
    ("white","red",10,5),
    ("red","white",18,7),
    ("white","red",6,3);


What i want is to sum white team score with sum().

And thank you in advance.

What I have tried:


i have tried to sum the score for team white, but it always sum the scoreA which is not always for team white as you saw with insert functions.
Posted
Updated 1-Mar-17 11:54am
Comments
Bryian Tan 1-Mar-17 13:25pm    
Where is your query? Something like this work?

SELECT teamA, SUM(scoreA) FROM Games
WHERE teamA = 'white'
GROUP BY teamA


Try:
SQL
SELECT SUM(CASE WHEN teamA = 'white' THEN scoreA ELSE 0 END + CASE WHEN teamB = 'white' THEN scoreB ELSE 0 END) FROM Games
 
Share this answer
 
Comments
CPallini 1-Mar-17 15:49pm    
Nice.
Your table breaks first normal form.
The columns teamA and teamB are the same column. There is nothing special about teamA; the combination white-red could be red-white without loss of meaning.
Note however that if you were using teamA to indicate home team that also breaks first normal form.
Once you normalize, summing the scores is trivial.

SQL
CREATE TABLE GameScores
(
  id     INTEGER,
  team   TEXT,
  score INTEGER
);
-- Primary key is id + team

INSERT INTO GameScores (id, team, score) 
  VALUES (1, "white", 10), (1, "red", 5),
         (2, "red", 18), (2, "white", 7), 
         (3, "white", 6), (3, "red", 3);

SELECT SUM(score) FROM GameScores WHERE team = "white";


I assume the team ids are for illustration only and that in practice you use neutral ids.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900