Vitor Barreto
Vitor Barreto

Reputation: 177

SQL Server sum multiple columns and group

I would like to in SQL Server to sum values from two different columns and grouping by team, but I'm not getting too much success.

Here's an example of the data:

Dataset example

I should be getting the following result:

And on the above image, how i would like it to be summed.

Here's the code I've written so far:

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

Upvotes: 0

Views: 325

Answers (1)

SqlZim
SqlZim

Reputation: 38063

You were pretty close, I think this is what you want:

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

Upvotes: 2

Related Questions