sql server 生成透视表

---恢复内容开始---

实例:

empid custid qty
2 A 52
3 A 20
1 B 20
2 B 27
1 C 34
3 C 22
3 D 30

 

要求转换后的透视图如下:

empid A B C D
1 NULL 20 34 NULL
2 52 27 NULL NULL
3 20 NULL 22 30

1.标准sql 进行透视转换

  select empid,

    sum(case when custid ='A' then qty End) AS A,

    sum(case when custid ='B' then qty End) AS B,

    sum(case when custid ='C' then qty End) AS C,

    sum(case when custid ='D' then qty End) AS D

  from dbo.Orders

  Group by empid;

2. 使用T-sql 特定的Pivot运算符

  select empid, A, B, C, D

  From (Select empid, custid, qty

      from dbo.Orders)AS D

     Pivot(Sum(qty) for custid, A, B, C, D)) As P;

3. 拼接sql 语句

    declare @str varchar(200);   

    set @str = 'select [empid], '

    select @str = @str + 'sum(case custid when '+quotename(custid,'''')+' then qty else 0 end) as '+quotename(custid)+','  from dbo.Orders group by custid

    select @str = left(@str, len(@str)-1)

    select @str = @str + '  from dbo.Orders group by [empid]'

    exec(@str)

参考文献:

  1.  Microsoft sql server 2008技术内幕: T-sql语言基础

  2.  http://www.cnblogs.com/shangfc/archive/2010/09/14/1826307.html

posted @ 2013-10-25 09:49  nosmall  阅读(484)  评论(0编辑  收藏  举报