结合行和取平均值

时间:2013-07-23 19:48:54

标签: sql sql-server sql-server-2008

我有一张看起来像的桌子

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

我想将行N和M一起称为X并取最大值max1和max2,同时在各自的列中取avg1,avg2和numb返回

#Sector  max1   avg1   max2  avg2  numb
C         133    14     45    3     27
X         174     6     77    2     17

2 个答案:

答案 0 :(得分:3)

尝试这种方式:

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')

答案 1 :(得分:2)

类似的东西:

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