您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

按年月统计并行列转换(ms sqlserver2005)

2025/6/27 10:27:18发布25次查看
按年月统计并行列转换(ms sqlserver2005) 1 创建表 create table [dbo].[orders]( [id] [int] identity(1,1) not null, [amount] [int] null, [year] [int] null, [month] [smallint] null, constraint [pk_orders] primary key clustered ( [id] asc )with
按年月统计并行列转换(ms sqlserver2005)
1 创建表
create table [dbo].[orders](
 [id] [int] identity(1,1) not null,
 [amount] [int] null,
 [year] [int] null,
 [month] [smallint] null,
 constraint [pk_orders] primary key clustered
(
 [id] asc
)with (pad_index  = off, statistics_norecompute  = off, ignore_dup_key = off, allow_row_locks  = on, allow_page_locks  = on) on [primary]
) on [primary]
2 初始化数据
insert into [orders]
select 100,2010,1
union all
select 200,2010,2
union all
select 200,2010,2
union all
select 200,2010,2
union all
select 180,2010,5
union all
select 100,2010,7
union all
select 150,2010,8
union all
select 150,2010,8
union all
select 150,2010,8
union all
select 108,2010,10
union all
select 100,2010,11
union all
select 108,2010,12
union all
select 200,2009,2
union all
select 180,2009,5
union all
select 100,2009,7
union all
select 150,2009,8
union all
select 150,2009,8
union all
select 150,2009,8
union all
select 108,2009,10
union all
select 100,2009,11
union all
select 108,2009,12
select * from [orders]
--------sql 2005------
select *
from
( select year,month,amount
from [orders]) p
pivot
(sum (amount)
for month in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) as amount
-------sql 2000-----
select year,
[1] = sum ( case when month ='1' then amount else 0 end ),
[2] = sum ( case when month ='2' then amount else 0 end ),
[3] = sum ( case when month ='3' then amount else 0 end ),
[4] = sum ( case when month ='4' then amount else 0 end ),
[5] = sum ( case when month ='5' then amount else 0 end ),
[6] = sum ( case when month ='6' then amount else 0 end ),
[7] = sum ( case when month ='7' then amount else 0 end ),
[8] = sum ( case when month ='8' then amount else 0 end ),
[9] = sum ( case when month ='9' then amount else 0 end ),
[10] = sum ( case when month ='10' then amount else 0 end ),
[10] = sum ( case when month ='10' then amount else 0 end ),
[12] = sum ( case when month ='12' then amount else 0 end ),
[count] = sum ( case when month '' then amount else 0 end )
from [orders]
group by year
有更好的方法欢迎贴上来,学习下
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product