日期:2014-05-18  浏览次数:20435 次

这样的SQL语句怎么写啊!
有这样结构的表格:表名为:test

类型         数量         小组
甲               10             A
乙               8               A
丙               9               A
丁               11             A
甲               12             B
乙               10             B
丙               9               B
丁               8               B

现在想得到这样的数据结果:
小组           甲             乙       丙     丁
A                 10             8         9       11
B                 12             10       9       8  
  这样的SQL,怎么写啊,请各位达人,指点迷津啊!在线等!



------解决方案--------------------
select 小组,
甲=max(case when 类型= '甲 ' then 数量 else 0 end),
乙=max(case when 类型= '乙 ' then 数量 else 0 end),
丙=max(case when 类型= '丙 ' then 数量 else 0 end),
丁=max(case when 类型= '丁 ' then 数量 else 0 end)
from tbName
group by 小组
------解决方案--------------------

create table T(类型 varchar(10), 数量 int, 小组 varchar(10))
insert T select '甲 ', 10, 'A '
union all select '乙 ' , 8, 'A '
union all select '丙 ', 9, 'A '
union all select '丁 ', 11, 'A '
union all select '甲 ', 12, 'B '
union all select '乙 ', 10, 'B '
union all select '丙 ', 9 , 'B '
union all select '丁 ', 8, 'B '

select 小组,
甲=max(case when 类型= '甲 ' then 数量 else 0 end),
乙=max(case when 类型= '乙 ' then 数量 else 0 end),
丙=max(case when 类型= '丙 ' then 数量 else 0 end),
丁=max(case when 类型= '丁 ' then 数量 else 0 end)
from T
group by 小组

--result
小组 甲 乙 丙 丁
---------- ----------- ----------- ----------- -----------
A 10 8 9 11
B 12 10 9 8

(2 row(s) affected)
------解决方案--------------------

create table T(类型 varchar(10), 数量 int, 小组 varchar(10))
insert T select '甲 ', 10, 'A '
union all select '乙 ' , 8, 'A '
union all select '丙 ', 9, 'A '
union all select '丁 ', 11, 'A '
union all select '甲 ', 12, 'B '
union all select '乙 ', 10, 'B '
union all select '丙 ', 9 , 'B '
union all select '丁 ', 8, 'B '