博客
关于我
SQL Server 列转行的实现
阅读量:286 次
发布时间:2019-03-03

本文共 1387 字,大约阅读时间需要 4 分钟。

在日常的工作中,尤其是涉及数据处理和分析的场景,我们常常需要将多行数据转化为单行数据。以下是一个关于SQL Server中列转行操作的示例,展示了如何将不同课程的成绩从表中转换为行数据。

一、创建表并插入数据

首先,我们创建一个名为stu_Score的表,包含学生姓名和三门课程的成绩。以下是具体操作:

if objectid('stu_Score') is nullbegin    create table stu_Score (        name varchar(10),        java int,        C# int,        python int    )endinsert into stu_Score values ('Dina', 82, 93, 90)insert into stu_Score values ('Joyce', 87, 80, 95)insert into stu_Score values ('Mandy', 93, 86, 90)

二、查看表中数据

执行以下查询可以查看表中当前数据:

select * from stu_Score

此时,表中数据如下:

name java C# python
Dina 82 93 90
Joyce 87 80 95
Mandy 93 86 90

三、实现数据的列转行

为了实现列转行,我们可以使用两种方法:

方法一:使用UNION ALL操作

select     name,    course = 'java',    score = javafrom stu_Scoreunion allselect     name,    course = 'C#',    score = C#from stu_Scoreunion allselect     name,    course = 'python',    score = pythonfrom stu_Score

此时,查询结果如下:

name course score
Dina java 82
Joyce java 87
Mandy java 93
Dina C# 93
Joyce C# 80
Mandy C# 86
Dina python 90
Joyce python 95
Mandy python 90

方法二:使用UNPIVOT操作

select     name,    course,    scorefrom stu_Scoreunpivot (score for course in ([java], [C#], [python]))

此时,查询结果如下:

name course score
Dina java 82
Dina C# 93
Dina python 90
Joyce java 87
Joyce C# 80
Joyce python 95
Mandy java 93
Mandy C# 86
Mandy python 90

两种方法的查询结果一致,均将原始表中的多列数据转换为行数据,便于后续的数据分析和呈现。

四、总结

通过上述两种方法,我们成功实现了将stu_Score表中的多列数据转换为行数据的操作。这两种方法各有特点,选择取决于具体的业务需求和数据结构。

转载地址:http://iwpl.baihongyu.com/

你可能感兴趣的文章
npm node pm2相关问题
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>
npm run build报Cannot find module错误的解决方法
查看>>
npm run build部署到云服务器中的Nginx(图文配置)
查看>>
npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
查看>>
npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
查看>>
npm scripts 使用指南
查看>>
npm should be run outside of the node repl, in your normal shell
查看>>
npm start运行了什么
查看>>
npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
查看>>
npm 下载依赖慢的解决方案(亲测有效)
查看>>
npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
查看>>
npm.taobao.org 淘宝 npm 镜像证书过期?这样解决!
查看>>
npm—小记
查看>>
npm上传自己的项目
查看>>
npm介绍以及常用命令
查看>>
NPM使用前设置和升级
查看>>
npm入门,这篇就够了
查看>>
npm切换到淘宝源
查看>>
npm切换源淘宝源的两种方法
查看>>