SQL Server对多个列和组

时间:2017-03-18 20:14:06

标签: sql sql-server

我想在SQL Server中对两个不同列的值进行求和并按团队进行分组,但是我没有取得太大的成功。

以下是数据示例:

Dataset example

I should be getting the following result:

在上图中,我希望如何总结。

这是我到目前为止编写的代码:

Select
    Fut.HomeTeam As Equipa,
    Sum(Fut.FTHG) As Golos
From 
    Database Fut
Group By 
    Fut.HomeTeam

Union All

Select
    Fut.AwayTeam As Equipa,
    Sum(Fut.FTAG) As Golos
From 
    Database Fut
Group By 
    Fut.AwayTeam
Order By 
    Golos Desc

1 个答案:

答案 0 :(得分:2)

你非常接近,我认为这就是你想要的:

select 
    Equipa
  , sum(Golos) as Golos
from (
  Select
    Fut.HomeTeam As Equipa,
    Fut.FTHG As Golos
  From Database Fut

  Union All
  Select
    Fut.AwayTeam As Equipa,
    Fut.FTAG As Golos
  From Database Fut
) u
Group By Equipa
Order By Sum(Golos) Desc