Classic SQL questions: Row to column < go >

Source: Internet
Author: User
Tags stmt

turn to Classic SQL problem: row to columnPosted 5 months ago (2015-09-19 17:49) Read (2905) | Comments (0) People collection This article, I want to collect likes 0

The school records the results, each person's choice course is different, and later will add the course, so do not need to take all the courses as a column. Database grade inside the data, for example, assume that each person's name is different, as the primary key. This article is based on MySQL, and other databases will have a slightly different syntax.

Database data:

Post-processing effects:

Here are three ways to do this:

Method One:

?
12345 SELECTDISTINCT a.name,(SELECTscoreFROMgrade bWHEREa.name=b.nameANDb.course=‘语文‘)AS‘语文‘,(SELECTscoreFROMgrade bWHEREa.name=b.nameANDb.course=‘数学‘)AS‘数学‘,(SELECTscoreFROMgrade bWHEREa.name=b.nameANDb.course=‘英语‘)AS‘英语‘FROMgrade a

Method Two:

?
12345 SELECTname,SUM(CASE courseWHEN ‘语文‘THENscoreEND)AS‘语文‘,SUM(CASE courseWHEN ‘数学‘THENscoreEND)AS‘数学‘,SUM(CASE courseWHEN ‘英语‘THENscoreEND)AS‘英语‘FROMgradeGROUPBYname


Method Three:

?
1234567891011121314151617181920212223242526 DELIMITER &&CREATE PROCEDURE sp_count()BEGIN#课程名称DECLARE course_n VARCHAR(20);#所有课程数量DECLARE count INT;#计数器DECLARE i INT DEFAULT 0;#拼接SQL字符串SET @s = ‘SELECT name‘;SET count = (SELECTCOUNT(distinct course) FROM grade);WHILE i < count DOSET course_n = (SELECT course FROM grade LIMIT i,1);SET @s = CONCAT(@s, ‘, SUM(CASE  course WHEN  ‘,‘\‘‘, course_n,‘\‘‘,‘ THEN score END )‘,‘ AS ‘,‘\‘‘,course_n,‘\‘‘);SET i = i+1;END WHILE;SET @s = CONCAT(@s, ‘ FROM grade GROUP BY name‘);#用于调试#SELECT @s;PREPARE stmt FROM @s;EXECUTE stmt;END&& call sp_count();



Method Analysis:

The first method uses table joins.
The second uses a grouping, which is processed separately for each grouping.
The third uses the stored procedure, is actually the second method dynamic, first calculates the quantity of all courses, then carries on the course query to each grouping.
It is obvious that the first two methods are hard-coded, and you need to modify the SQL after adding the course. And the third one doesn't have that kind of problem.

Note:

MySQL cannot remove another stored procedure in one stored procedure, only another stored procedure can be called
Originally wanted to write in method three: DROP PROCEDURE IF EXISTS sp_count (); This is wrong. Debugging when the wrong write, can only be manually deleted, and did not find a good method.

References:

    • Relive sql--row to column, make a career change
    • SQL statement for database row to column

2013-8-8 Update:

Method Two can also use the IF statement.
As shown below:

?
12345 SELECT name,SUM(IF (course = ‘语文‘ , score , null ) ) as ‘语文‘,SUM(IF (course = ‘数学‘ , score , null ) ) as ‘数学‘,SUM(IF (course = ‘英语‘ , score , null ) ) as ‘英语 ‘FROM grade GROUP BY name
    • if (EXPR1,EXPR2,EXPR3), if Expr1 is true (expr1<>0 and Expr1<>null), then if () returns EXPR2, otherwise it returns EXPR3. IF () returns a numeric or string value, depending on the context in which it is used.

Classic SQL questions: Row to column < go >

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.