最近在做一个数据统计,要求对一个表中的数据按照两个维度呈现,也就是传统的交叉表
比如,有一个问题表,有三个字段,(标题、问题类别、问题状态)
要求按照不同的类别,分别统计处各个状态的问题数量(如:产品问题中未处理的数量、服务问题中遗留问题数量等等)。
经过查找和尝试,终于生成了结果,现在分享给大家。
通过 Sql 2005 中的 Pivot 函数,可以方便的制作交叉表。
关于Pivot的用法,就不详细说了,大家可以百度一下,或者看sql server的帮助文档
下面是代码部分
--问题分类表
CREATE TABLE [dbo].[QuestionClass](
[QuestionClassID] [int] IDENTITY(1,1) NOT NULL,
[QuestionClassName] [nvarchar](50) NULL,
CONSTRAINT [PK_QuestionClass] PRIMARY KEY CLUSTERED
(
[QuestionClassID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--问题状态表
CREATE TABLE [dbo].[QuestionState](
[QuestionStateID] [int] IDENTITY(1,1) NOT NULL,
[QuestionStateName] [nvarchar](50) NULL,
CONSTRAINT [PK_QuestionState] PRIMARY KEY CLUSTERED
(
[QuestionStateID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--问题记录表
CREATE TABLE [dbo].[Question](
[QuestionID] [int] IDENTITY(1,1) NOT NULL,
[Topic] [nvarchar](50) NULL,
[ClassID] [int] NULL,
[StateID] [int] NULL,
CONSTRAINT [PK_Question] PRIMARY KEY CLUSTERED
(
[QuestionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--初始化状态数据
insert into QuestionState(QuestionStateName)
select '未处理' union all
select '已处理' union all
select '无效反馈'
--初始化类别数据
insert into QuestionClass(QuestionClassName)
select '产品问题' union all
select '销售问题' union all
select '服务问题' union all
select '其他问题'
--初始化问题数据
insert into Question(Topic,ClassID,St