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

你可能感兴趣的文章
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
nova基于ubs机制扩展scheduler-filter
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>