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

你可能感兴趣的文章
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
Nginx 结合 consul 实现动态负载均衡
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置清单(一篇够用)
查看>>
Nginx 配置解析:从基础到高级应用指南
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx之二:nginx.conf简单配置(参数详解)
查看>>
Nginx代理websocket配置(解决websocket异常断开连接tcp连接不断问题)
查看>>
Nginx代理初探
查看>>