SQL Server 2008中对汇总有明显的增强,有点像Oracle的语法了。请看下面五个例子:
假定场景如下:某几位员工在不同时间参加了不同的项目,获取了相应的收入,现在需要按各种分类进行统计。
基本表如下:
USE testDb2 GO
IF NOT OBJECT_ID('tb_Income') IS NULL DROP TABLE [tb_Income]
/****** Object: Table [dbo].[tb_Income] Script Date: 2012/4/5 8:19:21 ******/
CREATE TABLE [dbo].[tb_Income]( [TeamID] int not null, [PName] [Nvarchar](20) NOT NULL, [CYear] Smallint NOT NULL, [CMonth] TinyInt NOT NULL, [CMoney] Decimal (10,2) Not Null
)
GO INSERT [dbo].[tb_Income] SELECT 1,'胡一刀',2011,2,5600 union ALL SELECT 1,'胡一刀',2011,1,5678 union ALL SELECT 1,'胡一刀',2011,3,6798 union ALL SELECT 2,'胡一刀',2011,4,7800 union ALL SELECT 2,'胡一刀',2011,5,8899 union ALL SELECT 3,'胡一刀',2012,8,8877
union ALL SELECT 1,'苗人凤',2011,1,3455 union ALL SELECT 1,'苗人凤',2011,2,4567 union ALL SELECT 2,'苗人凤',2011,3,5676 union ALL SELECT 3,'苗人凤',2011,4,5600 union ALL SELECT 2,'苗人凤',2011,5,6788 union ALL SELECT 2,'苗人凤',2012,6,5679 union ALL SELECT 2,'苗人凤',2012,7,6785
union ALL SELECT 2,'张无忌',2011,2,5600 union ALL SELECT 2,'张无忌',2011,3,2345 union ALL SELECT 2,'张无忌',2011,5,12000 union ALL SELECT 3,'张无忌',2011,4,23456 union ALL SELECT 3,'张无忌