MySQL rows converted to columns

Source: Internet
Author: User

Http://www.cnblogs.com/acelove/archive/2004/11/29/70434.html mentions a method of row and column conversion, in fact, in 2005 there is a more readable notation, that is, using the pivot operator:

CREATE TABLE ABC
(
Student varchar (50),
Class varchar (50),
Grade int
)
INSERT into ABC
SELECT ' Sun Xiaomi ', ' math ', UNION all
SELECT ' Sun Xiaomi ', ' language ', UNION all
SELECT ' Sun Xiaomi ', ' English ', UNION all
SELECT ' Artuber ', ' math ', all
SELECT ' Artuber ', ' language ', UNION all
SELECT ' Artuber ', ' English ', UNION all
SELECT ' small ding ', ' math ', ' UNION all '
SELECT ' small ding ', ' Chinese ', UNION all
SELECT ' Little ding clang ', ' English ', 90

SELECT
Student
MAX (mathematics) as mathematics,
MAX (language) as language,
MAX (English) as English
From
(
SELECT
Student
Case class when ' math ' then grade END as math,
Case class when ' language ' then grade END as language,
Case class when ' English ' then grade END as English
From ABC
) as a
GROUP by Student
--Using the pivot operator
Select student,[Math] as ' math ', [language] as ' language ', [English] as ' English '
From
(SELECT * FROM ABC) as source
Pivot
(
SUM (grade)
For class in
([Mathematics],[Chinese],[English])
) as P


However, for a program that does not know the specific column name is not very good solution, generate dynamic SQL session (call sp_executesql), arm such as:

DECLARE @sql varchar (8000)
Set @sql = ' Select student, '
Select @sql = @sql + ' sum (case class "+class+" then grade else 0 end) as ' +class+ ', '
From (SELECT DISTINCT class from ABC) as a
Select @sql = Left (@sql, Len (@sql)-1) + ' from ABC GROUP by Student '
EXEC (@sql)

Yes, but with the current stored procedure call does not belong to a batch of commands, the definition of the CTE, the local temporary table can not access, it seems only to be placed in the business layer or the data layer to solve.

MySQL rows converted to columns

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.