2012-04-06 2 views
9

mysql에서 피벗 테이블을 만드는 방법을 알고 있지만 (아래 코드 예제 참조) 피벗 테이블의 열 수가 매우 크고 2000 정도이므로 tagnames를 입력하지 않으려면 어떻게해야합니까? ? - 그 목록을 생성하는 방법이 있습니까? 미리 감사드립니다.mysql의 pivot 테이블

drop table pivot; 
create table pivot SELECT time, 
     max(if(tagname = 'a', value, null)) AS 'a', 
     max(if(tagname = 'b', value, null)) AS 'b', 
     max(if(tagname = 'c', value, null)) AS 'c' 
    FROM test where tagname in ('a','b','c') 
GROUP BY time; 
select * from pivot; 
당신은 항상 :-)에게 정확히

#!/bin/sh 

mysql -BN test > /tmp/$$_tagnames.tmp <<SQL 
select distinct tagname from test; 
SQL 

cat > /tmp/$$_create_table.sql <<EOF 
drop table if exists pivot; 
create table pivot select 
EOF 

while read tag; do 
    echo "max(if(tagname = '$tag', value, null)) AS '$tag'," >> /tmp/$$_create_table.sql 
done < /tmp/$$_tagnames.tmp 

cat >> /tmp/$$_create_table.sql <<EOF 
time 
FROM test 
GROUP BY time; 
select * from pivot; 
EOF 

mysql -Bt test < /tmp/$$_create_table.sql 

rm /tmp/$$_create_table.sql 
rm /tmp/$$_tagnames.tmp 

데이터 수행하는 쉘 스크립트를 만들 수 있습니다

+3

모습을 ~에서 이 기사. http://buysql.com/mysql/14-how-to-automate-pivot-tables.html – GeoGo

답변

1

:

mysql> select * from test; 
+---------+-------+---------------------+ 
| tagname | value | time    | 
+---------+-------+---------------------+ 
| a  | foo | 2012-12-21 00:00:01 | 
| b  | foo | 2012-04-27 00:00:01 | 
| c  | bar | 2012-03-27 00:00:01 | 
| d  | bar | 2012-12-21 00:00:01 | 
+---------+-------+---------------------+ 
4 rows in set (0.00 sec) 

스크립트 출력 :

$ ./pivot.sh 
+------+------+------+------+---------------------+ 
| a | b | c | d | time    | 
+------+------+------+------+---------------------+ 
| NULL | NULL | bar | NULL | 2012-03-27 00:00:01 | 
| NULL | foo | NULL | NULL | 2012-04-27 00:00:01 | 
| foo | NULL | NULL | bar | 2012-12-21 00:00:01 | 
+------+------+------+------+---------------------+ 
+0

이것은 쉘 스크립팅의 영리한 사용이며이 패턴은 다른 언어에도 사용할 수 있습니다. –