本篇内容主要讲解“Sql Server中怎么实现行数据转为列显示”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Sql Server中怎么实现行数据转为列显示”吧!
场景:行数据的某列值想作为字段列显示
1、效果如下
2、解决方案
使用pivot进行行转列,以及结合分组
3、代码如下
select * from( select DeptName,InputCode from FWD_Department group by DeptName,InputCode) as apivot( max(InputCode) for DeptName in([随访中心],[全院],[家庭化产房],[妇科二],妇科一)) piv
创建表:
USE [test]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[FWD_Department]([id] [int] IDENTITY(1,1) NOT NULL,[DeptName] [varchar](50) NOT NULL,[InputCode] [nchar](10) NULL, CONSTRAINT [PK_one] PRIMARY KEY CLUSTERED ([DeptName] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO
表记录添加:
insert into one(DeptName,InputCode)values('随访中心','SFZX')insert into one(DeptName,InputCode)values('全院','QY')insert into one(DeptName,InputCode)values('家庭化产房','JTHCF')insert into one(DeptName,InputCode)values('妇科二','FKE')insert into one(DeptName,InputCode)values('妇科一','FKY')
到此,相信大家对“Sql Server中怎么实现行数据转为列显示”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!