博客
关于我
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/

你可能感兴趣的文章
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node exporter完整版
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
Node+Express连接mysql实现增删改查
查看>>
node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
查看>>
Node-RED中Button按钮组件和TextInput文字输入组件的使用
查看>>
Node-RED中Switch开关和Dropdown选择组件的使用
查看>>
Node-RED中使用html节点爬取HTML网页资料之爬取Node-RED的最新版本
查看>>
Node-RED中使用JSON数据建立web网站
查看>>
Node-RED中使用json节点解析JSON数据
查看>>
Node-RED中使用node-random节点来实现随机数在折线图中显示
查看>>
Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
查看>>