首页
随笔记录

分类

当前位置: 云海天教程网 > 技术新闻 > 随笔记录 >正文

SqlServer数据行转列

更新时间:2023-05-26  作者:佚名   来源: 网络转载

准备表和插入数据

CREATE TABLE [dbo].[Test](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Type] [nvarchar](30) NOT NULL,
	[Status] [nvarchar](30) NOT NULL,
	[AppNo] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_DocumentSet] 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],
 CONSTRAINT [unique_Test_Type_AppNo] UNIQUE NONCLUSTERED 
(
	[Type] ASC,
	[AppNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

insert into Test
select "type1", "status_a", "100021"
union all
select "type2", "status_b", "100021"
union all
select "type1", "status_b", "100022"
union all
select "type2", "status_c", "100022"
union all
select "type1", "status_a", "100023"
union all
select "type2", "status_c", "100023"
union all
select "type1", "status_e", "100024"
union all
select "type2", "status_n", "100024"
union all
select "type1", "status_b", "100025"
union all
select "type2", "status_y", "100025"
union all
select "type1", "status_e", "100026"
union all
select "type2", "status_c", "100027"
GO

查询当前数据

select * from Test

查询结果:
SqlServer数据行转列


当前数据行转列

select AppNo, max(case [Type] when N"type1" then status end) as "Type1 status", 
 max(case [Type] when N"type2" then status end) as "Type2 status"
FROM [dbo].[Test]
group by AppNo

查询结果:
SqlServer数据行转列

上一篇:backto 结 下一篇:vue3 组件传参
小编推荐
快速导航更多>>
JavaScript 教程 HTML5 教程 CSS3 教程 jQuery 教程 Vue.js 教程 Node.js 教程 SQL 教程 C 教程 PHP 教程 Linux 教程 Docker 教程 Nginx 教程 Python 教程 Java 教程

云海天教程网 版权所有

 陕公网安备 61050202000585号

陕ICP备14013131号-3