日期:2014-05-17 浏览次数:20673 次
create table tb(时间 datetime,省份 varchar(20), 数据 int)
insert into tb
select '2013-8-1', '陕西', 50 union all
select '2013-8-2', '陕西', 50 union all
select '2013-8-3', '陕西', 50 union all
select '2013-8-3', '河南', 50 union all
select '2013-8-4', '陕西', 50 union all
select '2013-8-5', '陕西', 50 union all
select '2013-8-5', '河南', 50 union all
select '2013-8-5', '山西', 50
go
declare @sql varchar(8000)
set @sql = ',sum(数据) as [全国]'
select @sql = @sql + ',sum(case when 省份='''+省份+''' then 数据 else 0 end) ['+省份+']'
from tb
group by 省份
order by 省份 desc
select @sql = 'select 时间'+@sql +
'from tb group by 时间'
exec( @sql)
/*
时间 全国 陕西 山西 河南
2013-08-01 00:00:00.000 50 50 0 0
2013-08-02 00:00:00.000 50 50 0 0
2013-08-03 00:00:00.000 100 50 0 50
2013-08-04 00:00:00.000 50 50 0 0
2013-08-05 00:00:00.000 150 50 50 50
*/
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date &nbs