可以将一个表的行与另一个表的行相加吗?

huangapple go评论61阅读模式
英文:

Is it possible to sum a row from a table to a row to another table?

问题

可以使用单个SQL查询来实现这个目标吗?

英文:

I have 2 tables made like so:

NickName Points
Player 1 15
Player 2 8
NickName Points
Player 1 33
Player 2 22

and I need to get this table:

NickName Points
Player 1 48
Player 2 30

Is it possible to do such thing using a single query in SQL?

答案1

得分: 1

将两个表连接起来,使用 UNION ALL 对 Points 列进行聚合操作。

SELECT NickName, SUM(Points) as Points
FROM (
  SELECT NickName, Points FROM table1
  UNION ALL
  SELECT NickName, Points FROM table2
) as combined_tables
GROUP BY NickName;

你可以在以下链接中查看示例:db<>fiddle

英文:

Join the two tables and perform an aggregation on the Points column using the UNION ALL

SELECT NickName, SUM(Points) as Points
FROM (
  SELECT NickName, Points FROM table1
  UNION ALL
  SELECT NickName, Points FROM table2
) as combined_tables
GROUP BY NickName;

db<>fiddle output

答案2

得分: 1

理想的设计是将数据放在同一张表中,同时有第三列来定义当前分离数据的内容(例如事件/比赛等)。这将允许您单独选择数据或进行聚合。

例如:

选择NickName、Points from mytable WHERE eventID = 1

或者

选择NickName、SUM(Points) from mytable GROUP BY NickName

英文:

The ideal design would be to have the data in the same table with a 3rd column defining whatever it is that currently separates your data (i.e. event/game etc). This would allow you to select the data either separately or aggregate.

E.g.

SELECT NickName, Points from mytable WHERE eventID = 1

or

SELECT NickName, SUM(Points) from mytable GROUP BY NickName

huangapple
  • 本文由 发表于 2023年3月4日 07:51:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定