Home Database Mysql Tutorial 表格的横纵转

表格的横纵转

Jun 07, 2016 pm 02:56 PM
sql Horizontal portrait sheet Record statement

SQL语句中,横向记录转成纵向列, 纵向列转成横向记录。 无 ##############行转列-example 1 ,学生成绩###############创建数据库表CREATE TABLE StudentScores ( UserName NVARCHAR(20), Subject NVARCHAR(30), Score FLOAT ) ; #插入模拟数据INSERT INTO St

SQL语句中,横向记录转成纵向列, 纵向列转成横向记录。
##############行转列-example 1 ,学生成绩##############
#创建数据库表
CREATE  TABLE StudentScores  (
      UserName         NVARCHAR(20),            
      Subject          NVARCHAR(30),              
      Score            FLOAT                
      )  ;      
#插入模拟数据
INSERT INTO StudentScores SELECT 'Nick', '语文', 80 ; 
INSERT INTO StudentScores SELECT 'Nick', '数学', 90 ;
INSERT INTO StudentScores SELECT 'Nick', '英语', 70 ; 
INSERT INTO StudentScores SELECT 'Nick', '生物', 85 ;
INSERT INTO StudentScores SELECT 'Kent', '语文', 80 ;
INSERT INTO StudentScores SELECT 'Kent', '数学', 90 ;
INSERT INTO StudentScores SELECT 'Kent', '英语', 70 ;
INSERT INTO StudentScores SELECT 'Kent', '生物', 85 ;
#查询每个学生的各科成绩
SELECT UserName, 
       MAX(CASE Subject WHEN '语文' THEN Score ELSE 0 END) AS '语文',        
       MAX(CASE Subject WHEN '数学' THEN Score ELSE 0 END) AS '数学',        
       MAX(CASE Subject WHEN '英语' THEN Score ELSE 0 END) AS '英语',        
       MAX(CASE Subject WHEN '生物' THEN Score ELSE 0 END) AS '生物' 
FROM StudentScores
GROUP BY UserName ;

##############行转列-example 2 ,游戏玩家充值##############
#创建数据库表
CREATE TABLE Inpours  (
       ID             INT AUTO_INCREMENT,
       UserName          NVARCHAR(20),        
       CreateTime     DATETIME,               
       PayType         NVARCHAR(20),            
       Money             DECIMAL,             
       IsSuccess         BIT,    
       CONSTRAINT PK_Inpours_ID PRIMARY KEY(ID)  
)   ;
#插入模拟数据
INSERT INTO Inpours(UserName , CreateTime , PayType , Money , IsSuccess) SELECT '张三', '2010-05-01', '支付宝', 50, 1  ;
INSERT INTO Inpours(UserName , CreateTime , PayType , Money , IsSuccess) SELECT '张三', '2010-06-14', '支付宝', 50, 1  ;
INSERT INTO Inpours(UserName , CreateTime , PayType , Money , IsSuccess) SELECT '张三', '2010-06-14', '手机短信', 100, 1  ;
INSERT INTO Inpours(UserName , CreateTime , PayType , Money , IsSuccess) SELECT '李四', '2010-06-14', '手机短信', 100, 1  ;  
INSERT INTO Inpours(UserName , CreateTime , PayType , Money , IsSuccess) SELECT '李四', '2010-07-14', '支付宝', 100, 1  ;  
INSERT INTO Inpours(UserName , CreateTime , PayType , Money , IsSuccess) SELECT '王五', '2010-07-14', '工商银行卡', 100, 1  ;  
INSERT INTO Inpours(UserName , CreateTime , PayType , Money , IsSuccess) SELECT '赵六', '2010-07-14', '建设银行卡', 100, 1  ;
#要求按日期、支付方式来统计充值金额信息
select CreateTime,
       CASE PayType WHEN '支付宝' THEN SUM(Money) ELSE 0 END AS '支付宝',       
       CASE PayType WHEN '手机短信' THEN SUM(Money) ELSE 0 END AS '手机短信',       
       CASE PayType WHEN '工商银行卡' THEN SUM(Money) ELSE 0 END AS '工商银行卡',       
       CASE PayType WHEN '建设银行卡' THEN SUM(Money) ELSE 0 END AS '建设银行卡'       
FROM Inpours 
GROUP BY CreateTime, PayType

##############列转行-example 1 ,供货信息##############
#创建数据库表
CREATE TABLE ProgrectDetail  (
      ProgrectName         NVARCHAR(20),      
      OverseaSupply        INT,              
      NativeSupply         INT,                
      SouthSupply          INT,               
      NorthSupply          INT             
)
#插入模拟数据
   INSERT INTO ProgrectDetail 
   SELECT 'A', 100, 200, 50, 50  
   UNION ALL SELECT 'B', 200, 300, 150, 150  
   UNION ALL SELECT 'C', 159, 400, 20, 320  
   UNION ALL SELECT 'D', 250, 30, 15, 15
#
SELECT ProgrectName, 'OverseaSupply' AS Supplier, MAX(OverseaSupply) AS 'SupplyNum' FROM ProgrectDetail  GROUP BY ProgrectName  
UNION ALL 
SELECT ProgrectName, 'NativeSupply' AS Supplier, MAX(NativeSupply) AS 'SupplyNum' FROM ProgrectDetail  GROUP BY ProgrectName  
UNION ALL 
SELECT ProgrectName, 'SouthSupply' AS Supplier, MAX(SouthSupply) AS 'SupplyNum' FROM ProgrectDetail  GROUP BY ProgrectName 
UNION ALL 
SELECT ProgrectName, 'NorthSupply' AS Supplier, MAX(NorthSupply) AS 'SupplyNum' FROM ProgrectDetail  GROUP BY ProgrectName
Copy after login
Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Steps to adjust the format of pictures inserted in PPT tables Steps to adjust the format of pictures inserted in PPT tables Mar 26, 2024 pm 04:16 PM

1. Create a new PPT file and name it [PPT Tips] as an example. 2. Double-click [PPT Tips] to open the PPT file. 3. Insert a table with two rows and two columns as an example. 4. Double-click on the border of the table, and the [Design] option will appear on the upper toolbar. 5. Click the [Shading] option and click [Picture]. 6. Click [Picture] to pop up the fill options dialog box with the picture as the background. 7. Find the tray you want to insert in the directory and click OK to insert the picture. 8. Right-click on the table box to bring up the settings dialog box. 9. Click [Format Cells] and check [Tile images as shading]. 10. Set [Center], [Mirror] and other functions you need, and click OK. Note: The default is for pictures to be filled in the table

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

Where can I view the records of things I have purchased on Pinduoduo? How to view the records of purchased products? Where can I view the records of things I have purchased on Pinduoduo? How to view the records of purchased products? Mar 12, 2024 pm 07:20 PM

Pinduoduo software provides a lot of good products, you can buy them anytime and anywhere, and the quality of each product is strictly controlled, every product is genuine, and there are many preferential shopping discounts, allowing everyone to shop online Simply can not stop. Enter your mobile phone number to log in online, add multiple delivery addresses and contact information online, and check the latest logistics trends at any time. Product sections of different categories are open, search and swipe up and down to purchase and place orders, and experience convenience without leaving home. With the online shopping service, you can also view all purchase records, including the goods you have purchased, and receive dozens of shopping red envelopes and coupons for free. Now the editor has provided Pinduoduo users with a detailed online way to view purchased product records. method. 1. Open your phone and click on the Pinduoduo icon.

How to make a table for sales forecast How to make a table for sales forecast Mar 20, 2024 pm 03:06 PM

Being able to skillfully make forms is not only a necessary skill for accounting, human resources, and finance. For many sales staff, learning to make forms is also very important. Because the data related to sales is very large and complex, and it cannot be simply recorded in a document to explain the problem. In order to enable more sales staff to be proficient in using Excel to make tables, the editor will introduce the table making issues about sales forecasting. Friends in need should not miss it! 1. Open [Sales Forecast and Target Setting], xlsm, to analyze the data stored in each table. 2. Create a new [Blank Worksheet], select [Cell], and enter [Label Information]. [Drag] downward and [Fill] the month. Enter [Other] data and click [

Usage of division operation in Oracle SQL Usage of division operation in Oracle SQL Mar 10, 2024 pm 03:06 PM

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

How to set WPS value to automatically change color according to conditions_Steps to set WPS table value to automatically change color according to condition How to set WPS value to automatically change color according to conditions_Steps to set WPS table value to automatically change color according to condition Mar 27, 2024 pm 07:30 PM

1. Open the worksheet and find the [Start]-[Conditional Formatting] button. 2. Click Column Selection and select the column to which conditional formatting will be added. 3. Click the [Conditional Formatting] button to bring up the option menu. 4. Select [Highlight conditional rules]-[Between]. 5. Fill in the rules: 20, 24, dark green text with dark fill color. 6. After confirmation, the data in the selected column will be colored with corresponding numbers, text, and cell boxes according to the settings. 7. Conditional rules without conflicts can be added repeatedly, but for conflicting rules WPS will replace the previously established conditional rules with the last added rule. 8. Repeatedly add the cell columns after [Between] rules 20-24 and [Less than] 20. 9. If you need to change the rules, you can just clear the rules and then reset the rules.

Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

See all articles