1

I have a table that looks like

#Sector  max1   avg1   max2  avg2  numb
C         133    14     45    3     27
N         174     9     77    3     18
M         63      3     28    1     16

I would like to join rows N and M together call it X and take the max value of max1 and max2 while taking the avg of avg1, avg2, and numb in their respective columns to return

#Sector  max1   avg1   max2  avg2  numb
C         133    14     45    3     27
X         174     6     77    2     17
Radu Gheorghiu
  • 20,049
  • 16
  • 72
  • 107
euge1220
  • 235
  • 1
  • 3
  • 9

2 Answers2

3

Try this way:

select sector, max1,avg1,max2,avg2,numb
from tab
where sector not in ('M','N')
union all
select 'X' as sector, max(max1),avg(avg1),max(max2),avg(avg2),avg(numb)
from tab
where sector in ('M','N')
Robert
  • 25,425
  • 8
  • 67
  • 81
2

something like:

select 
  case when sector in ('N','M') then 'X' else sector end sect,
  max(max1) max1,
  avg(avg1) avg1,
  max(max2) max2,
  avg(avg2) avg2,
  avg(numb) numb
from tabname 
group by 
  case when sector in ('N','M') then 'X' else sector end
Ian Kenney
  • 6,376
  • 1
  • 25
  • 44
  • Couldn't you `GROUP BY sect`? – Jeromy French Jul 24 '13 at 01:48
  • Ah hah. Thanks--I've been using PostgreSQL for the past year, so my MSSQL learnin's are starting to fade. So `GROUP BY 1` (column poisition) would also be possible, but prone to problems down the road if the query is changed and the returned columns are moved around... – Jeromy French Jul 24 '13 at 13:32