`
lanfei
  • 浏览: 150517 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

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

 
阅读更多
http://blog.csdn.net/huwei2003/article/details/5984747

按年月统计并行列转换(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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics