search
HomeDatabaseMysql Tutorial数据库中的行列转换

数据库中的行列转换

Jun 07, 2016 pm 03:29 PM
teacherdatabaseInquiresystemConvertquestion

问题描述 在评教系统中查询教师成绩处涉及到了数据的行转列应用,首先介绍下行转列要解决的问题: 我们数据库中存储的数据结构类似为: 而最后我们要达到的查询效果为: 我们将课程列分成了三列,而对应的分数列的数据作为记录插入到了相应课程的后面。 功能



问题描述

在评教系统中查询教师成绩处涉及到了数据的行转列应用,首先介绍下行转列要解决的问题:

我们数据库中存储的数据结构类似为:

而最后我们要达到的查询效果为:

我们将课程列分成了三列,而对应的分数列的数据作为记录插入到了相应课程的后面。

功能来源

为什么会出现这样的需求呢?

数据库设计的过程中为了满足用户的动态要求(添加字段),可以采用定义字段名表,定义一个字段值的表,以达到用静态表达动态。也就是说以数据库表纵向的增加替代原有的横向延伸,即记录条数的增加替代字段增加。

这样的设计带来了灵活,但同时带来了统计分析的麻烦,因为统计分析时有可能需要显示字段展开的情况。如评教系统中的具体实现:

由于考核项目会进行动态的添加删除,因此设置的考核项目表,存储对教师的考核项目

而存储教师评教分数的表需要获取考核项目数据,存储图示为:

最终需要的显示效果是要将考核项目列为标题,而分值作为记录添加到对应的考核项目下。

此处我们我们通过将动态变化的考核项目作为新的表的记录来存储带来了设计的灵活性,而显示的时候却要进行行列的转换才能得到想要的结果。

具体实现

查找相关资料进行实现,明白了行转列又分成了静态和动态之分,静态的是不需要扩展的,很容易实现,而针对评教系统中的功能则是对应的动态实现。

针对第一个实例

1.通过执行字符串的拼接实现动态行转列

--变量按sql语言顺序赋值

declare @sql varchar(500)

set @sql = 'select 姓名'

select @sql = @sql+',max(case 课程 when '''+ 课程 +''' then 分数 else 0 end)['+课程+']'

from(select distinct 课程 from tb)a	--同from tb group by课程,默认按课程名排序

set @sql= @sql + ' from tb group by 姓名'

exec(@sql)

2.使用isnull、pivot函数

declare @sql varchar(8000)

--获得课程集合

select @sql=isnull(@sql+',','')+ 课程 from tb group by 课程           

set @sql='select * from tb pivot (max(分数) for 课程 in ('+@sql+')) a'

exec(@sql)

3.添加算总分、平均分的要求

declare @sql varchar(8000)

select @sql=isnull(@sql+',','')+ 课程 from tb group by 课程

set @sql='select m.* , n.总分,n.平均分 from

(select * from (select * from tb) a pivot (max(分数) for 课程 in ('+

 @sql+')) b) m ,

(select 姓名,sum(分数)总分, cast(avg(分数*1.0) as decimal(18,2)) 平均分 from tb group by 姓名) n

where m.姓名= n.姓名'

exec(@sql)

新得小结

虽然评教系统中已经实现了对行列数据的转换,但想要使用另外一种方法进行实现。进行了对行转列功能的搜索实现之后,在转接到评教系统上的应用上来还是碰到了很多问题,到现在仍没有完全解决,只得暂时先放一放了。对数据库的灵活设计也有了一定的体会,在考虑灵活性的同时也要考虑用户的体验度的。对行列互相转换的还是需要更多的思考呀。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools