2014-07-15 2 views
0

내 쿼리 :쿼리 피벗

set @sql = NULL; 
select 
    group_concat(distinct 
    concat(
    'max(if(first.study = ''', 
    study, ''', first.avg_scores, NULL)) as ', 
    study 
) 
) into @sql 
from `table`; 

SET @sql = concat('select first.name, 
       ', @sql, ' 
       from `table` first 
       join `table` second 
        on first.name = second.name 
       group by first.name'); 

prepare stmt from @sql; 
execute stmt; 
deallocate prepare stmt; 

데이터 열에서 "연구"

================================= 
    name | study | avg_scores 
================================= 
    alfa  c   75 
    beta  c   70 
    alfa  php  85 
    beta  php  90 

및 결과 : 진정한.

=========================== 
    name | c | php 
=========================== 
    alfa  75  85 
    beta  70  90 

내가 같은 테이블에 데이터가 문제 :

=================================== 
    name | study  | avg_scores 
=================================== 
    alfa junior c   75 
    beta junior c   70 
    alfa junior php  85 
    beta junior php  90 

오류 : "당신은 당신의 SQL 구문에 오류가있다;에 대한 귀하의 MySQL 서버 버전 에 해당하는 설명서를 확인을 두 번째 줄에서 주니어 php로 'c, max (if (first.study ='junior php ', first.avg_scores, NULL))를 사용할 올바른 구문은 다음과 같습니다.

so : 내 검색어를 수정하는 방법?

답변

0

열 이름에 공백을 사용할 수 없으므로 식별자를 이스케이프해야합니다. 다음은 이름에 큰 따옴표를 사용합니다 (백틱을 사용할 수도 있습니다).

set @sql = NULL; 
select group_concat(distinct concat('max(if(first.study = ''', study, 
            ''', first.avg_scores, NULL)) as "', study, '"' 
---------------------------------------------------------------------^ ----------^  
            ) 
        ) into @sql 
from `table`; 

SET @sql = concat('select first.name, ', @sql, ' 
        from `table` first join `table` second on first.name = second.name 
        group by first.name'); 
+0

감사합니다. gordon, 그것이 작동합니다. :) – user3747046