对表SQL中的特定值进行计数和求和

时间:2018-04-26 07:20:29

标签: sql

我正在尝试寻找一种方法来对查询中的特定行求和。我找到了" group by"可以做的工作,但我不明白如何使用它

    TABLE TEAM: 
    TeamID TeamName  
      1     Apes
      2     Bird
      3     Cat
      4     Dog
      5     Eagle
      6     Fish
      7     Giraffe
      8     Hawk
      9     Insect
    ==========================
    Table RECORD: 
    Date  MATCH_A  MATCH_B  A_SCORE  B_SCORE
    2/1      2        8        2        0
    2/1      5        9        4        1
    3/1      6        4        3        3
    3/1      1        3        1        2
    4/1      1        9        1        1
    5/1      2        4        0        3 
    5/1      3        8        1        0
    6/1      7        6        1        0
    6/1      3        5        1        1
    7/1      2        9        3        2                     
    7/1      4        1        1        0

例如,第1组完全打3场比赛(MATCH A + MATCH B)。 我想展示球队有多少场比赛以及球队得到多少比赛,以便比赛A完全

  TeamID TeamName  TotalMatch
      1     Apes        3
      2     Bird        3
      3     Cat         3
      4     Dog         3 
      5     Eagle       2 
      6     Fish        2
      7     Giraffe     1
      8     Hawk        2
      9     Insect      3
==============================
   TeamID TeamName  Total_Match_A_SCORE
      1     Apes        2
      2     Bird        5
      3     Cat         2
      4     Dog         1 
      5     Eagle       4 
      6     Fish        3
      7     Giraffe     1
      8     Hawk        0
      9     Insect      0

但是我的查询无法相应地显示该值,但查询会在每行中添加所有值

SELECT TEAMID, TEAMNAME, COUNT(MATCH_A, MATCH_B) AS TotalMatch
FROM TEAM, RECORD
GROUP BY TEAMID, TEAMNAME

SELECT TEAMID, TEAMNAME, SUM(A_SCORE) AS Total_MatchA_SCORE
FROM TEAM, RECORD
GROUP BY TEAMID, TEAMNAME

3 个答案:

答案 0 :(得分:0)

您的查询似乎缺少连接两个表的where子句。请修改您的查询,如下所示:

SELECT TEAMID, TEAMNAME, COUNT(MATCH_A, MATCH_B) AS TotalMatch
FROM TEAM, RECORD
WHERE TEAM.TEAMID=RECORD.MATCH_A OR TEAM.TEAMID=RECORD.MATCH_B
GROUP BY TEAMID, TEAMNAME

SELECT TEAMID, TEAMNAME, SUM(A_SCORE) AS Total_MatchA_SCORE
FROM TEAM, RECORD
WHERE TEAM.TEAMID=RECORD.MATCH_A OR TEAM.TEAMID=RECORD.MATCH_B
GROUP BY TEAMID, TEAMNAME

答案 1 :(得分:0)

这比看起来要复杂一些。首先,您需要学习正确的标准JOIN语法。 从不FROM子句中使用逗号。

您需要UNION ALL。如果您想要一行中的值,则需要在GROUP BY

之前执行此操作
select t.teamid, t.teamname, count(*) AS TotalMatch, sum(a_score) as a_score
from team t join
     ((select match_a as teamid, a_score
       from record
      ) union all
      (select match_b as teamid, 0 a_score
       from record
      )
     ) m
     on t.teamid = m.teamid
group by t.teamid, t.teamname; 

另请注意使用表别名和限定列名。

答案 2 :(得分:0)

df.set_index(['user_id','date']).sort_index()

只是使用了连接和大小写来输出你想要的数据。希望这会有所帮助。