简体   繁体   English

根据其他列中的条件求和多个列-SQL Teradata

[英]Sum multiple columns based on criteria from other columns - SQL Teradata

I would like to get a total of the scores from columns 3 & 4 for each of the counties in columns 1 & 2 from the table shown below: 我想从下表中获取第1列和第2列中每个县的第3列和第4列的总分:

County1    |    County2     |   Player1_Score   |   Player2_Score
Norfolk    |    Hampshire   |       5           |       7
Suffolk    |    Norfolk     |       10          |       6
Hampshire  |    Suffolk     |       16          |       12
Norfolk    |    Suffolk     |       78          |       50
Hampshire  |    Norfolk     |       4           |       8
Suffolk    |    Hampshire   |       9           |       19

So the results I would like to see would be as follows: 因此,我希望看到的结果如下:

Norfolk     |       97
Suffolk     |       77
Hampshire   |       32

Can anyone please help with this? 谁能帮忙吗? I tried a SELECT/GROUP BY query but am fairly new to SQL and couldn't get the results I wanted. 我尝试执行SELECT/GROUP BY查询,但对SQL来说还是一个新手,无法获得所需的结果。

Many thanks 非常感谢

Try this: 尝试这个:

SELECT County, SUM(Score) AS TotalScore
FROM (                   
  SELECT County1 AS County, Player1_Score AS Score
  FROM mytable

  UNION ALL

  SELECT County2, Player2_Score
  FROM mytable) AS t
GROUP BY County
ORDER BY TotalScore DESC

Demo here 在这里演示

SEL CNTRY,SUM(SUM1) FROM
(
SEL COUNTRY1 AS CNTRY, SUM(player_score_1) AS SUM1 FROM VT1
GROUP BY 1
UNION 
SEL COUNTRY2 AS CNTRY, SUM(player_score_2) FROM VT1
GROUP BY 1
) A
GROUP BY 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM