0

I am a begginer using this kind of query in SQL Server and I have a big table similar as I'm showing, the trouble that I have is that I don't know how to group and sum at the same time, I need to sum the SUP with every SIG with the code

  CODE      SIG  SUP
R501004002  BCO  30
R501004002  BCO  31.27
R501004008  BCO  34.09
R501004008  BCO  35.94
R501004003  MET  42
R501004020  RIP  42.5
R501004039  BCO  47.44
R501004020  RIP  68.56

The result that I want to show is something like this

CODE        BCO    MET  RIP
R501004002  61.27  0     0
R501004003  0      42    0
R501004008  70.03  0     0
R501004020   0     0     111.06
R501004039  47.44  0     0

I group the code

  • 1
    You may be after a dynamic pivot table. stack has several such examples. However, if you only have 3 sig's... then you could use case statements. so do you have more than 3 sigs? – xQbert Oct 13 '15 at 20:03

1 Answers1

0

Assuming only 3 sigs...

SELECT code
  , sum(case when sig = 'BCO' then sup else 0 end) as BCO
  , sum(case when sig = 'MET' then sup else 0 end) as MET
  , sum(case when sig = 'RIP' then sup else 0 end) as RIP
FROM tableName
GROUP BY code

otherwise use a dynamic pivot as exampled here

Community
  • 1
  • 1
xQbert
  • 34,733
  • 2
  • 41
  • 62