将分组的行转换为SQL Server中的列

时间:2016-08-03 07:12:50

标签: sql sql-server

我的SQL Server数据库中有这样的表格:

o_owner period                  price
-------------------------------------
00035   2016-08-05$$$2016-08-12 10
00035   2016-08-13$$$2016-08-19 20
00035   2016-08-20$$$2016-08-26 30
00036   2016-08-05$$$2016-08-12 11
00036   2016-08-13$$$2016-08-19 12
00036   2016-08-20$$$2016-08-26 13
00037   2016-08-05$$$2016-08-12 21
00037   2016-08-13$$$2016-08-19 23
00037   2016-08-20$$$2016-08-26 29

我需要这样的结果

o_owner 2016-08-05$$$2016-08-12 2016-08-13$$$2016-08-19 2016-08-20$$$2016-08-26
--------------------------------------------------------------------
00035   10                      20                      30
00036   11                      12                      13
00037   21                      23                      29

我花了几个小时,使用数据透视表,临时表等,仍然无法构建它。

最后在固定的coloumn模式我可以构建它,仍然需要动态coloumn的解决方案

select a.o_owner
,(select price from myTable where period='2016-08-05$$$2016-08-12' and   o_owner = a.o_owner) as "2016-08-05$$$2016-08-12"
,(select price from myTable where period='2016-08-13$$$2016-08-19' and o_owner = a.o_owner) as "2016-08-13$$$2016-08-19"
,(select price from myTable where period='2016-08-20$$$2016-08-26' and  o_owner = a.o_owner) as "2016-08-20$$$2016-08-26"
from myTable a
group by a.o_owner

我想用循环来计算期间'然后重建查询并执行类似

的操作
declare @sql as text
declare @sqlAdd as varchar(512)
@sqlAdd = --***looping here to count and built query for 'period' coloumn dynamically***
@sql = 'select a.o_owner' + 
@sqlAdd +
'from myTable a
group by a.o_owner'
execute(@sql)

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:0)

如果您有固定列,则可以使用大小写,例如:

   select o_owner, sum(p1) p1, sum(p2) p2, sum(p3) p3 from (
     select 
        o_owner,
        case when period = '2016-08-05$$$2016-08-12' then price end p1, 
        case when period = '2016-08-13$$$2016-08-19' then price end p2, 
        case when period = '2016-08-20$$$2016-08-26' then price end p3
     from mytable
   ) x
   group by o_owner

(我使用p1 - p3作为句点名称以减少输入)