数据库中的行列转换
问题描述 在评教系统中查询教师成绩处涉及到了数据的行转列应用,首先介绍下行转列要解决的问题: 我们数据库中存储的数据结构类似为: 而最后我们要达到的查询效果为: 我们将课程列分成了三列,而对应的分数列的数据作为记录插入到了相应课程的后面。 功能
问题描述
在评教系统中查询教师成绩处涉及到了数据的行转列应用,首先介绍下行转列要解决的问题:
我们数据库中存储的数据结构类似为:
而最后我们要达到的查询效果为:
我们将课程列分成了三列,而对应的分数列的数据作为记录插入到了相应课程的后面。
功能来源
为什么会出现这样的需求呢?
数据库设计的过程中为了满足用户的动态要求(添加字段),可以采用定义字段名表,定义一个字段值的表,以达到用静态表达动态。也就是说以数据库表纵向的增加替代原有的横向延伸,即记录条数的增加替代字段增加。
这样的设计带来了灵活,但同时带来了统计分析的麻烦,因为统计分析时有可能需要显示字段展开的情况。如评教系统中的具体实现:
由于考核项目会进行动态的添加删除,因此设置的考核项目表,存储对教师的考核项目
而存储教师评教分数的表需要获取考核项目数据,存储图示为:
最终需要的显示效果是要将考核项目列为标题,而分值作为记录添加到对应的考核项目下。
此处我们我们通过将动态变化的考核项目作为新的表的记录来存储带来了设计的灵活性,而显示的时候却要进行行列的转换才能得到想要的结果。
具体实现
查找相关资料进行实现,明白了行转列又分成了静态和动态之分,静态的是不需要扩展的,很容易实现,而针对评教系统中的功能则是对应的动态实现。
针对第一个实例
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)
新得小结
虽然评教系统中已经实现了对行列数据的转换,但想要使用另外一种方法进行实现。进行了对行转列功能的搜索实现之后,在转接到评教系统上的应用上来还是碰到了很多问题,到现在仍没有完全解决,只得暂时先放一放了。对数据库的灵活设计也有了一定的体会,在考虑灵活性的同时也要考虑用户的体验度的。对行列互相转换的还是需要更多的思考呀。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











On July 29, at the roll-off ceremony of AITO Wenjie's 400,000th new car, Yu Chengdong, Huawei's Managing Director, Chairman of Terminal BG, and Chairman of Smart Car Solutions BU, attended and delivered a speech and announced that Wenjie series models will be launched this year In August, Huawei Qiankun ADS 3.0 version was launched, and it is planned to successively push upgrades from August to September. The Xiangjie S9, which will be released on August 6, will debut Huawei’s ADS3.0 intelligent driving system. With the assistance of lidar, Huawei Qiankun ADS3.0 version will greatly improve its intelligent driving capabilities, have end-to-end integrated capabilities, and adopt a new end-to-end architecture of GOD (general obstacle identification)/PDP (predictive decision-making and control) , providing the NCA function of smart driving from parking space to parking space, and upgrading CAS3.0

On April 11, Huawei officially announced the HarmonyOS 4.2 100-machine upgrade plan for the first time. This time, more than 180 devices will participate in the upgrade, covering mobile phones, tablets, watches, headphones, smart screens and other devices. In the past month, with the steady progress of the HarmonyOS4.2 100-machine upgrade plan, many popular models including Huawei Pocket2, Huawei MateX5 series, nova12 series, Huawei Pura series, etc. have also started to upgrade and adapt, which means that there will be More Huawei model users can enjoy the common and often new experience brought by HarmonyOS. Judging from user feedback, the experience of Huawei Mate60 series models has improved in all aspects after upgrading HarmonyOS4.2. Especially Huawei M

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Recently, Huawei announced that it will launch a new smart wearable product equipped with Xuanji sensing system in September, which is expected to be Huawei's latest smart watch. This new product will integrate advanced emotional health monitoring functions. The Xuanji Perception System provides users with a comprehensive health assessment with its six characteristics - accuracy, comprehensiveness, speed, flexibility, openness and scalability. The system uses a super-sensing module and optimizes the multi-channel optical path architecture technology, which greatly improves the monitoring accuracy of basic indicators such as heart rate, blood oxygen and respiration rate. In addition, the Xuanji Sensing System has also expanded the research on emotional states based on heart rate data. It is not limited to physiological indicators, but can also evaluate the user's emotional state and stress level. It supports the monitoring of more than 60 sports health indicators, covering cardiovascular, respiratory, neurological, endocrine,

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

According to news on July 9, testers of Xiaomi.EU, a well-known official version of the system, recently discovered that Xiaomi has recently taken new measures to restrict devices sold in mainland China from installing the Xiaomi international version. If a user attempts to install the international version of the system on a Chinese version of the device, the device will display an unsupported message during boot and will be unable to enter the system. This mechanism can identify the market version to which the hardware belongs. For Xiaomi mobile phones sold in mainland China, if it is detected that the international version of the system is installed, it will not be able to start normally. Test results show that the flashed device will display "Unsupported software" (unsupported software) in the boot wizard and prompt that using this version may bring security risks. Currently, Xiaomi has
