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

你可能感兴趣的文章
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
nmap 使用方法详细介绍
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
nmap指纹识别要点以及又快又准之方法
查看>>
Nmap渗透测试指南之指纹识别与探测、伺机而动
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>