Sqlite总结特定名称的所有分数 [英] Sqlite sum all score for a specific name

查看:71
本文介绍了Sqlite总结特定名称的所有分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

我需要帮助总结表格中特定名字的所有值。



table:



 CREATE TABLE游戏

id INTEGER PRIMARY KEY,
teamA TEXT,
teamB TEXT,
得分A INTEGER,
得分B INTEGER)};





插入:



 INSERT INTO游戏
(teamA,teamB,scoreA,scoreB)
VALUES
(白色,红色,10,5),
(红色,白色,18,7),
(白色,红色,6,3);





我想要的是将白队得分与总和()相加。



并提前谢谢你。



我尝试过的事情:





i试图将团队白色的分数加起来,但它总是将得分A总和,这对于团队白色并不总是如你所看到的插入函数。

解决方案

尝试:

  SELECT  SUM( CASE   WHEN  teamA = '  white' 那么 scoreA  ELSE   0   END  +  CASE   WHEN  teamB = '  white'  那么 scoreB  ELSE   0   END  FROM 游戏


你的表打破了第一个正常形式。

列teamA和teamB是同一列。 teamA没什么特别之处;白红色的组合可以是红白色而不会失去意义。

但是请注意,如果你使用teamA来表示主队也打破了第一个正常状态。

一旦你正常化,总结得分是微不足道的。



<前lang =SQL> 创建 < span class =code-keyword> TABLE GameScores

id INTEGER,
team TEXT
得分INTEGER
);
- 主键是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(得分) FROM GameScores WHERE team = white;





我假设团队ID仅用于说明,实际上你使用中性ID。


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.

解决方案

Try:

SELECT SUM(CASE WHEN teamA = 'white' THEN scoreA ELSE 0 END + CASE WHEN teamB = 'white' THEN scoreB ELSE 0 END) FROM Games


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.

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.


这篇关于Sqlite总结特定名称的所有分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆