日期:2014-05-19  浏览次数:20616 次

请问sql语句能实现类似于数据透视表的查询吗??
表结构
人员             品种           数量
甲                   A                 10
甲                   A                 3
甲                   B                 20
乙                   A                 5
乙                   B                 7
乙                   B                 4


要查询出结果
人员\品种               A                   B
甲                           13                 20
乙                             5                 11
谢谢各位了

------解决方案--------------------
select 人员 as 人员\品种,sum(case when 品种= 'a ' then 数量 else 0 end) as a,sum(case when 品种= 'b ' then 数量 else 0 end) from tablename group by 人员
------解决方案--------------------
select 人员 as 人员\品种,sum(case when 品种= 'A ' then 数量 end) as A,sum(case when 品种= 'B ' then 数量 end) as B from tablename group by 人员

------解决方案--------------------
select distinct 人员 as 人员\品种,
sum(case 品种 when 'A ' then 数量 else 0 end) as A,
sum(case 品种 when 'B ' then 数量 else 0 end) as B
from tablename
group by 人员
order by 人员
------解决方案--------------------
declare @a table(人员 char(10),品种 char(10),数量 int)
insert into @a select '甲 ', 'A ', 10 union all
select '甲 ', 'A ', 3 union all
select '甲 ', 'B ', 20 union all
select '乙 ', 'A ', 5 union all
select '乙 ', 'B ', 7 union all
select '乙 ', 'B ', 4
select 人员 as [人员\品种],sum(case when 品种= 'a ' then 数量 else 0 end) as a,sum(case when 品种= 'b ' then 数量 else 0 end)as b from @a group by 人员
result:
人员\品种 a b
---------- ----------- -----------
甲 13 20
乙 5 11

(所影响的行数为 2 行)


------解决方案--------------------
调试通过:

select distinct 人员 as [人员\品种],
sum(case 品种 when 'A ' then 数量 else 0 end) as A,
sum(case 品种 when 'B ' then 数量 else 0 end) as B
from tablename
group by 人员
order by 人员
------解决方案--------------------

create table T(人员 nvarchar(10), 品种 char(1), 数量 int)
insert T select '甲 ' , 'A ', 10
union all select '甲 ', 'A ', 3
union all select '甲 ', 'B ', 20